forked from olamedia/nokogiri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nokogiri.php
311 lines (303 loc) · 8.82 KB
/
nokogiri.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
<?php
/*
* This file is part of the zero package.
* Copyright (c) 2012 olamedia <[email protected]>
*
* This source code is release under the MIT License.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Simple HTML parser
*
* @author olamedia <[email protected]>
*/
class nokogiri implements IteratorAggregate{
const
regexp =
"/(?P<tag>[a-z0-9]+)?(\[(?P<attr>\S+)=(?P<value>[^\]]+)\])?(#(?P<id>[^\s:>#\.]+))?(\.(?P<class>[^\s:>#\.]+))?(:(?P<pseudo>(first|last|nth)-child)(\((?P<expr>[^\)]+)\))?)?\s*(?P<rel>>)?/isS"
;
protected $_source = '';
/**
* @var DOMDocument
*/
protected $_dom = null;
/**
* @var DOMDocument
*/
protected $_tempDom = null;
/**
* @var DOMXpath
* */
protected $_xpath = null;
/**
* @var libxmlErrors
*/
protected $_libxmlErrors = null;
protected static $_compiledXpath = array();
public function __construct($htmlString = ''){
$this->loadHtml($htmlString);
}
public function getRegexp(){
$tag = "(?P<tag>[a-z0-9]+)?";
$attr = "(\[(?P<attr>\S+)=(?P<value>[^\]]+)\])?";
$id = "(#(?P<id>[^\s:>#\.]+))?";
$class = "(\.(?P<class>[^\s:>#\.]+))?";
$child = "(first|last|nth)-child";
$expr = "(\((?P<expr>[^\)]+)\))";
$pseudo = "(:(?P<pseudo>".$child.")".$expr."?)?";
$rel = "\s*(?P<rel>>)?";
$regexp = "/".$tag.$attr.$id.$class.$pseudo.$rel."/isS";
return $regexp;
}
public static function fromHtml($htmlString){
$me = new self();
$me->loadHtml($htmlString);
return $me;
}
public static function fromHtmlNoCharset($htmlString){
$me = new self();
$me->loadHtmlNoCharset($htmlString);
return $me;
}
public static function fromDom($dom){
$me = new self();
$me->loadDom($dom);
return $me;
}
public function loadDom($dom){
$this->_dom = $dom;
}
public function loadHtmlNoCharset($htmlString = ''){
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->preserveWhiteSpace = false;
if (strlen($htmlString)){
libxml_use_internal_errors(true);
$this->_libxmlErrors = null;
$dom->loadHTML('<?xml encoding="UTF-8">'.$htmlString);
// dirty fix
foreach ($dom->childNodes as $item){
if ($item->nodeType == XML_PI_NODE){
$dom->removeChild($item); // remove hack
break;
}
}
$dom->encoding = 'UTF-8'; // insert proper
$this->_libxmlErrors = libxml_get_errors();
libxml_clear_errors();
}
$this->loadDom($dom);
}
public function loadHtml($htmlString = ''){
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->preserveWhiteSpace = false;
if (strlen($htmlString)){
libxml_use_internal_errors(true);
$this->_libxmlErrors = null;
$dom->loadHTML($htmlString);
$this->_libxmlErrors = libxml_get_errors();
libxml_clear_errors();
}
$this->loadDom($dom);
}
public function getErrors(){
return $this->_libxmlErrors;
}
function __invoke($expression){
return $this->get($expression);
}
public function get($expression, $compile = true){
/*if (strpos($expression, ' ') !== false){
$a = explode(' ', $expression);
foreach ($a as $k=>$sub){
$a[$k] = $this->getXpathSubquery($sub);
}
return $this->getElements(implode('', $a));
}*/
return $this->getElements($this->getXpathSubquery($expression, false, $compile));
}
protected function getNodes(){
}
public function getDom($asIs = false){
if ($asIs){
return $this->_dom;
}
if ($this->_dom instanceof DOMDocument){
return $this->_dom;
}elseif ($this->_dom instanceof DOMNodeList || $this->_dom instanceof DOMElement){
if ($this->_tempDom === null){
$this->_tempDom = new DOMDocument('1.0', 'UTF-8');
$root = $this->_tempDom->createElement('root');
$this->_tempDom->appendChild($root);
if($this->_dom instanceof DOMNodeList){
foreach ($this->_dom as $domElement){
$domNode = $this->_tempDom->importNode($domElement, true);
$root->appendChild($domNode);
}
}else{
$domNode = $this->_tempDom->importNode($this->_dom, true);
$root->appendChild($domNode);
}
}
return $this->_tempDom;
}
}
protected function getXpath(){
if ($this->_xpath === null){
$this->_xpath = new DOMXpath($this->getDom());
}
return $this->_xpath;
}
public function getXpathSubquery($expression, $rel = false, $compile = true){
if ($compile){
$key = $expression.($rel?'>':'*');
if (isset(self::$_compiledXpath[$key])){
return self::$_compiledXpath[$key];
}
}
$query = '';
if (preg_match(self::regexp, $expression, $subs)){
$brackets = array();
if (isset($subs['id']) && '' !== $subs['id']){
$brackets[] = "@id='".$subs['id']."'";
}
if (isset($subs['attr']) && '' !== $subs['attr']){
$attrValue = isset($subs['value']) && !empty($subs['value'])?$subs['value']:'';
$brackets[] = "@".$subs['attr']."='".$attrValue."'";
}
if (isset($subs['class']) && '' !== $subs['class']){
$brackets[] = 'contains(concat(" ", normalize-space(@class), " "), " '.$subs['class'].' ")';
}
if (isset($subs['pseudo']) && '' !== $subs['pseudo']){
if ('first-child' === $subs['pseudo']){
$brackets[] = '1';
}elseif ('last-child' === $subs['pseudo']){
$brackets[] = 'last()';
}elseif ('nth-child' === $subs['pseudo']){
if (isset($subs['expr']) && '' !== $subs['expr']){
$e = $subs['expr'];
if('odd' === $e){
$brackets[] = '(position() -1) mod 2 = 0 and position() >= 1';
}elseif('even' === $e){
$brackets[] = 'position() mod 2 = 0 and position() >= 0';
}elseif(preg_match("/^[0-9]+$/", $e)){
$brackets[] = 'position() = '.$e;
}elseif(preg_match("/^((?P<mul>[0-9]+)n\+)(?P<pos>[0-9]+)$/is", $e, $esubs)){
if (isset($esubs['mul'])){
$brackets[] = '(position() -'.$esubs['pos'].') mod '.$esubs['mul'].' = 0 and position() >= '.$esubs['pos'].'';
}else{
$brackets[] = ''.$e.'';
}
}
}
}
}
$query = ($rel?'/':'//').
((isset($subs['tag']) && '' !== $subs['tag'])?$subs['tag']:'*').
(($c = count($brackets))?
($c>1?'[('.implode(') and (', $brackets).')]':'['.implode(' and ', $brackets).']')
:'')
;
$left = trim(substr($expression, strlen($subs[0])));
if ('' !== $left){
$query .= $this->getXpathSubquery($left, isset($subs['rel'])?'>'===$subs['rel']:false, $compile);
}
}
if ($compile){
self::$_compiledXpath[$key] = $query;
}
return $query;
}
protected function getElements($xpathQuery){
if (strlen($xpathQuery)){
$nodeList = $this->getXpath()->query($xpathQuery);
if ($nodeList === false){
throw new Exception('Malformed xpath');
}
return self::fromDom($nodeList);
}
}
public function toDom($asIs = false){
return $this->getDom($asIs);
}
public function toXml(){
return $this->getDom()->saveXML();
}
public function toArray($xnode = null){
$array = array();
if ($xnode === null){
if ($this->_dom instanceof DOMNodeList){
foreach ($this->_dom as $node){
$array[] = $this->toArray($node);
}
return $array;
}
$node = $this->getDom();
}else{
$node = $xnode;
}
if (in_array($node->nodeType, array(XML_TEXT_NODE,XML_COMMENT_NODE))){
return $node->nodeValue;
}
if ($node->hasAttributes()){
foreach ($node->attributes as $attr){
$array[$attr->nodeName] = $attr->nodeValue;
}
}
if ($node->hasChildNodes()){
foreach ($node->childNodes as $childNode){
$array[$childNode->nodeName][] = $this->toArray($childNode);
}
}
if ($xnode === null){
$a = reset($array);
return reset($a); // first child
}
return $array;
}
public function getIterator(){
$a = $this->toArray();
return new ArrayIterator($a);
}
protected function _toTextArray($node = null, $skipChildren = false, $singleLevel = true){
$array = array();
if ($node === null){
if ($this->_dom instanceof DOMNodeList){
foreach ($this->_dom as $node){
if ($singleLevel){
$array = array_merge($array, $this->_toTextArray($node, $skipChildren, $singleLevel));
}else{
$array[] = $this->_toTextArray($node, $skipChildren, $singleLevel);
}
}
return $array;
}
$node = $this->getDom();
}
if (XML_TEXT_NODE === $node->nodeType){
return array($node->nodeValue);
}
if (!$skipChildren){
if ($node->hasChildNodes()){
foreach ($node->childNodes as $childNode){
if ($singleLevel){
$array = array_merge($array, $this->_toTextArray($childNode, $skipChildren, $singleLevel));
}else{
$array[] = $this->_toTextArray($childNode, $skipChildren, $singleLevel);
}
}
}
}
return $array;
}
public function toTextArray($skipChildren = false, $singleLevel = true){
return $this->_toTextArray($this->_dom, $skipChildren, $singleLevel);
}
public function toText($glue = ' ', $skipChildren = false){
return implode($glue, $this->toTextArray($skipChildren, true));
}
}
/*$saw = new nokogiri();
echo $saw->getXpathSubquery('#boo #ge > #id:nth-child(3n+5)');
echo "\r\n";*/