-
Notifications
You must be signed in to change notification settings - Fork 0
/
SevenLeggedSpider.php
105 lines (80 loc) · 3.05 KB
/
SevenLeggedSpider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
// Requires PECL HTTP.
// Require PEAR Net::URL2
require_once( 'Net/URL2.php' );
class SevenLeggedSpider {
public function getUrlAsDom( $url ) {
$response = $this->get( $url );
$body = SevenLeggedSpider::getResponseBody( $response );
$character_encoding = SevenLeggedSpider::getCharacterEncoding( $response );
$dom = SevenLeggedSpider::slurpHtml( $body, $character_encoding );
return $dom;
}
public static function slurpXml( $xml ) {
$dom = new DomDocument();
$dom->strictErrorChecking = false;
$dom->recover = true;
// TODO: Any way around error suppression?
@$dom->loadXML( $xml );
return $dom;
}
public static function slurpHtml( $html ) {
$dom = new DomDocument();
$dom->strictErrorChecking = false;
$dom->recover = true;
// TODO: Any way around error suppression?
@$dom->loadHTML( $html );
return $dom;
}
public static function getCharacterEncoding( $response ) {
$content_type = $response->headers['Content-Type'];
$parsed = http_parse_params( $content_type );
if ( !empty( $parsed->params[1]['charset'] ) ) {
return $parsed->params[1]['charset'];
}
else {
return 'ISO-8859-1';
}
}
public static function getResponseBody( $response ) {
return $response->body;
}
public static function getNodesByXpath( $dom, $query ) {
$xpath = new DOMXPath( $dom );
$nodes = $xpath->query( $query );
return $nodes;
}
public function get( $url, $data = null ) {
$response = http_get( $url, array(), $info );
$parsed = http_parse_message( $response );
return $parsed;
}
public function post( $url, $data = array() ) {
$response = http_post( $url, $data );
$parsed = http_parse_message( $response );
return $parsed;
}
public static function getBaseUrl( $dom, $document_url ) {
$base_url = $document_url;
$nodes = self::getNodesByXpath( $dom, '//base/@href' );
if ( $nodes && $nodes->item(0) ) {
$base_url_override = $nodes->item(0)->value;
}
$parsed = parse_url( $base_url );
if ( !empty( $base_url_override ) ) {
$parsed = parse_url( $base_url_override );
}
$scheme = !empty( $parsed['scheme'] ) ? $parsed['scheme'] : 'http';
$host = $parsed['host'];
$port = !empty( $parsed['port'] ) ? ':'.$parsed['port'] : '';
$path = dirname( $parsed['path'] );
$path = preg_replace( '/(.*[^\/])$/', '$1/', $path );
$base_url = "${scheme}://${host}${port}/${path}";
return $base_url;
}
public static function resolveUrl( $relative_url, $base_url ) {
$base_url = new Net_URL2( $base_url );
return $base_url->resolve( $relative_url )->getURL();
}
}
?>