-
Notifications
You must be signed in to change notification settings - Fork 38
/
SimpleDOM.php
1084 lines (931 loc) · 25.1 KB
/
SimpleDOM.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
Copyright 2009 The SimpleDOM authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* @package SimpleDOM
* @version $Id: SimpleDOM.php 60 2010-04-01 06:34:58Z simpledom.dev $
* @link $URL: https://simpledom.googlecode.com/svn/trunk/SimpleDOM.php $
*/
/**
* Alias for simplexml_load_file()
*
* @return SimpleDOM
*/
function simpledom_load_file($filename)
{
$args = func_get_args();
if (isset($args[0]) && !isset($args[1]))
{
$args[1] = 'SimpleDOM';
}
return call_user_func_array('simplexml_load_file', $args);
}
/**
* Alias for simplexml_load_string()
*
* @return SimpleDOM
*/
function simpledom_load_string($string)
{
$args = func_get_args();
if (isset($args[0]) && !isset($args[1]))
{
$args[1] = 'SimpleDOM';
}
return call_user_func_array('simplexml_load_string', $args);
}
/**
* @package SimpleDOM
*/
class SimpleDOM extends SimpleXMLElement
{
//=================================
// Factories
//=================================
/**
* Create a SimpleDOM object from a HTML string
*
* @param string $source HTML source
* @param mixed &$errors Passed by reference. Will be replaced by an array of
* LibXMLError objects if applicable
* @return SimpleDOM
*/
static public function loadHTML($source, &$errors = null)
{
return self::fromHTML('loadHTML', $source, $errors);
}
/**
* Create a SimpleDOM object from a HTML file
*
* @param string $filename Path/URL to HTML file
* @param mixed &$errors Passed by reference. Will be replaced by an array of
* LibXMLError objects if applicable
* @return SimpleDOM
*/
static public function loadHTMLFile($filename, &$errors = null)
{
return self::fromHTML('loadHTMLFile', $filename, $errors);
}
//=================================
// DOM stuff
//=================================
/** @ignore **/
public function __call($name, $args)
{
$passthrough = array(
// From DOMElement
'getAttribute' => 'method',
'getAttributeNS' => 'method',
'getElementsByTagName' => 'method',
'getElementsByTagNameNS' => 'method',
'hasAttribute' => 'method',
'hasAttributeNS' => 'method',
'removeAttribute' => 'method',
'removeAttributeNS' => 'method',
'setAttribute' => 'method',
'setAttributeNS' => 'method',
// From DOMNode
'appendChild' => 'insert',
'insertBefore' => 'insert',
'replaceChild' => 'insert',
'cloneNode' => 'method',
'getLineNo' => 'method',
'hasAttributes' => 'method',
'hasChildNodes' => 'method',
'isSameNode' => 'method',
'lookupNamespaceURI'=> 'method',
'lookupPrefix' => 'method',
'normalize' => 'method',
'removeChild' => 'method',
'nodeName' => 'property',
'nodeValue' => 'property',
'nodeType' => 'property',
'parentNode' => 'property',
'childNodes' => 'property',
'firstChild' => 'property',
'lastChild' => 'property',
'previousSibling' => 'property',
'nextSibling' => 'property',
'namespaceURI' => 'property',
'prefix' => 'property',
'localName' => 'property',
'textContent' => 'property'
);
$dom = dom_import_simplexml($this);
if (!isset($passthrough[$name]))
{
if (method_exists($dom, $name))
{
throw new BadMethodCallException('DOM method ' . $name . '() is not supported');
}
if (property_exists($dom, $name))
{
throw new BadMethodCallException('DOM property ' . $name . ' is not supported');
}
throw new BadMethodCallException('Undefined method ' . get_class($this) . '::' . $name . '()');
}
switch ($passthrough[$name])
{
case 'insert':
if (isset($args[0])
&& $args[0] instanceof SimpleXMLElement)
{
$args[0] = $dom->ownerDocument->importNode(dom_import_simplexml($args[0]), true);
}
// no break; here
case 'method':
foreach ($args as &$arg)
{
if ($arg instanceof SimpleXMLElement)
{
$arg = dom_import_simplexml($arg);
}
}
unset($arg);
$ret = call_user_func_array(array($dom, $name), $args);
break;
case 'property':
$ret = $dom->$name;
break;
}
if ($ret instanceof DOMText)
{
return $ret->textContent;
}
if ($ret instanceof DOMNode)
{
if ($ret instanceof DOMAttr)
{
/**
* Methods that affect attributes can't return the attributes themselves. Instead,
* we make them chainable
*/
return $this;
}
return simplexml_import_dom($ret, get_class($this));
}
if ($ret instanceof DOMNodeList)
{
$class = get_class($this);
$list = array();
$i = -1;
while (++$i < $ret->length)
{
$node = $ret->item($i);
$list[$i] = ($node instanceof DOMText) ? $node->textContent : simplexml_import_dom($node, $class);
}
return $list;
}
return $ret;
}
//=================================
// DOM convenience methods
//=================================
/**
* Add a new sibling before this node
*
* This is a convenience method. The same result can be achieved with
* <code>
* $node->parentNode()->insertBefore($new, $node);
* </code>
*
* @param SimpleXMLElement $new New node
* @return SimpleDOM The inserted node
*/
public function insertBeforeSelf(SimpleXMLElement $new)
{
$tmp = dom_import_simplexml($this);
$node = $tmp->ownerDocument->importNode(dom_import_simplexml($new), true);
return simplexml_import_dom($this->insertNode($tmp, $node, 'before'), get_class($this));
}
/**
* Add a new sibling after this node
*
* This is a convenience method. The same result can be achieved with
* <code>
* $node->parentNode()->insertBefore($new, $node->nextSibling());
* </code>
*
* @param SimpleXMLElement $new New node
* @return SimpleDOM The inserted node
*/
public function insertAfterSelf(SimpleXMLElement $new)
{
$tmp = dom_import_simplexml($this);
$node = $tmp->ownerDocument->importNode(dom_import_simplexml($new), true);
return simplexml_import_dom($this->insertNode($tmp, $node, 'after'), get_class($this));
}
/**
* Delete this node from document
*
* This is a convenience method. The same result can be achieved with
* <code>
* $node->parentNode()->removeChild($node);
* </code>
*
* @return void
*/
public function deleteSelf()
{
$tmp = dom_import_simplexml($this);
if ($tmp->isSameNode($tmp->ownerDocument->documentElement))
{
throw new BadMethodCallException('deleteSelf() cannot be used to delete the root node');
}
$tmp->parentNode->removeChild($tmp);
}
/**
* Remove this node from document
*
* This is a convenience method. The same result can be achieved with
* <code>
* $node->parentNode()->removeChild($node);
* </code>
*
* @return SimpleDOM The removed node
*/
public function removeSelf()
{
$tmp = dom_import_simplexml($this);
if ($tmp->isSameNode($tmp->ownerDocument->documentElement))
{
throw new BadMethodCallException('removeSelf() cannot be used to remove the root node');
}
$node = $tmp->parentNode->removeChild($tmp);
return simplexml_import_dom($node, get_class($this));
}
/**
* Replace this node
*
* This is a convenience method. The same result can be achieved with
* <code>
* $node->parentNode()->replaceChild($new, $node);
* </code>
*
* @param SimpleXMLElement $new New node
* @return SimpleDOM Replaced node on success
*/
public function replaceSelf(SimpleXMLElement $new)
{
$old = dom_import_simplexml($this);
$new = $old->ownerDocument->importNode(dom_import_simplexml($new), true);
$node = $old->parentNode->replaceChild($new, $old);
return simplexml_import_dom($node, get_class($this));
}
/**
* Delete all elements matching a XPath expression
*
* @param string $xpath XPath expression
* @return integer Number of nodes removed
*/
public function deleteNodes($xpath)
{
if (!is_string($xpath))
{
throw new InvalidArgumentException('Argument 1 passed to deleteNodes() must be a string, ' . gettype($xpath) . ' given');
}
$nodes = $this->_xpath($xpath);
if (isset($nodes[0]))
{
$tmp = dom_import_simplexml($nodes[0]);
if ($tmp->isSameNode($tmp->ownerDocument->documentElement))
{
unset($nodes[0]);
}
}
foreach ($nodes as $node)
{
$node->deleteSelf();
}
return count($nodes);
}
/**
* Remove all elements matching a XPath expression
*
* @param string $xpath XPath expression
* @return array Array of removed nodes on success or FALSE on failure
*/
public function removeNodes($xpath)
{
if (!is_string($xpath))
{
throw new InvalidArgumentException('Argument 1 passed to removeNodes() must be a string, ' . gettype($xpath) . ' given');
}
$nodes = $this->_xpath($xpath);
if (isset($nodes[0]))
{
$tmp = dom_import_simplexml($nodes[0]);
if ($tmp->isSameNode($tmp->ownerDocument->documentElement))
{
unset($nodes[0]);
}
}
$return = array();
foreach ($nodes as $node)
{
$return[] = $node->removeSelf();
}
return $return;
}
/**
* Remove all elements matching a XPath expression
*
* @param string $xpath XPath expression
* @param SimpleXMLElement $new Replacement node
* @return array Array of replaced nodes on success or FALSE on failure
*/
public function replaceNodes($xpath, SimpleXMLElement $new)
{
if (!is_string($xpath))
{
throw new InvalidArgumentException('Argument 1 passed to replaceNodes() must be a string, ' . gettype($xpath) . ' given');
}
$nodes = array();
foreach ($this->_xpath($xpath) as $node)
{
$nodes[] = $node->replaceSelf($new);
}
return $nodes;
}
/**
* Copy all attributes from a node to current node
*
* @param SimpleXMLElement $src Source node
* @param bool $overwrite If TRUE, overwrite existing attributes.
* Otherwise, ignore duplicate attributes
* @return SimpleDOM Current node
*/
public function copyAttributesFrom(SimpleXMLElement $src, $overwrite = true)
{
$dom = dom_import_simplexml($this);
foreach (dom_import_simplexml($src)->attributes as $attr)
{
if ($overwrite
|| !$dom->hasAttributeNS($attr->namespaceURI, $attr->nodeName))
{
$dom->setAttributeNS($attr->namespaceURI, $attr->nodeName, $attr->nodeValue);
}
}
return $this;
}
/**
* Clone all children from a node and add them to current node
*
* This method takes a snapshot of the children nodes then append them in order to avoid infinite
* recursion if the destination node is a descendant of or the source node itself
*
* @param SimpleXMLElement $src Source node
* @param bool $deep If TRUE, clone descendant nodes as well
* @return SimpleDOM Current node
*/
public function cloneChildrenFrom(SimpleXMLElement $src, $deep = true)
{
$src = dom_import_simplexml($src);
$dst = dom_import_simplexml($this);
$doc = $dst->ownerDocument;
$fragment = $doc->createDocumentFragment();
foreach ($src->childNodes as $child)
{
$fragment->appendChild($doc->importNode($child->cloneNode($deep), $deep));
}
$dst->appendChild($fragment);
return $this;
}
/**
* Move current node to a new parent
*
* ATTENTION! using references to the old node will screw up the original document
*
* @param SimpleXMLElement $dst Target parent
* @return SimpleDOM Current node
*/
public function moveTo(SimpleXMLElement $dst)
{
return simplexml_import_dom(dom_import_simplexml($dst), get_class($this))->appendChild($this->removeSelf());
}
/**
* Return the first node of the result of an XPath expression
*
* @param string $xpath XPath expression
* @return mixed SimpleDOM object if any node was returned, NULL otherwise
*/
public function firstOf($xpath)
{
$nodes = $this->xpath($xpath);
return (isset($nodes[0])) ? $nodes[0] : null;
}
//=================================
// DOM extra
//=================================
/**
* Insert a CDATA section
*
* @param string $content CDATA content
* @param string $mode Where to add this node: 'append' to current node,
* 'before' current node or 'after' current node
* @return SimpleDOM Current node
*/
public function insertCDATA($content, $mode = 'append')
{
$this->insert('CDATASection', $content, $mode);
return $this;
}
/**
* Insert a comment node
*
* @param string $content Comment content
* @param string $mode Where to add this node: 'append' to current node,
* 'before' current node or 'after' current node
* @return SimpleDOM Current node
*/
public function insertComment($content, $mode = 'append')
{
$this->insert('Comment', $content, $mode);
return $this;
}
/**
* Insert a text node
*
* @param string $content CDATA content
* @param string $mode Where to add this node: 'append' to current node,
* 'before' current node or 'after' current node
* @return SimpleDOM Current node
*/
public function insertText($content, $mode = 'append')
{
$this->insert('TextNode', $content, $mode);
return $this;
}
/**
* Insert raw XML data
*
* @param string $xml XML to insert
* @param string $mode Where to add this tag: 'append' to current node,
* 'before' current node or 'after' current node
* @return SimpleDOM Current node
*/
public function insertXML($xml, $mode = 'append')
{
$tmp = dom_import_simplexml($this);
$fragment = $tmp->ownerDocument->createDocumentFragment();
/**
* Disable error reporting
*/
$use_errors = libxml_use_internal_errors(true);
if (!$fragment->appendXML($xml))
{
libxml_use_internal_errors($use_errors);
throw new InvalidArgumentException(libxml_get_last_error()->message);
}
libxml_use_internal_errors($use_errors);
$this->insertNode($tmp, $fragment, $mode);
return $this;
}
/**
* Insert a Processing Instruction
*
* The content of the PI can be passed either as string or as an associative array.
*
* @param string $target Target of the processing instruction
* @param string|array $data Content of the processing instruction
* @return bool TRUE on success, FALSE on failure
*/
public function insertPI($target, $data = null, $mode = 'before')
{
$tmp = dom_import_simplexml($this);
$doc = $tmp->ownerDocument;
if (isset($data))
{
if (is_array($data))
{
$str = '';
foreach ($data as $k => $v)
{
$str .= $k . '="' . htmlspecialchars($v) . '" ';
}
$data = substr($str, 0, -1);
}
else
{
$data = (string) $data;
}
$pi = $doc->createProcessingInstruction($target, $data);
}
else
{
$pi = $doc->createProcessingInstruction($target);
}
if ($pi !== false)
{
$this->insertNode($tmp, $pi, $mode);
}
return $this;
}
/**
* Set several attributes at once
*
* @param array $attr Attributes as name => value pairs
* @param string $ns Namespace for the attributes
* @return SimpleDOM Current node
*/
public function setAttributes(array $attr, $ns = null)
{
$dom = dom_import_simplexml($this);
foreach ($attr as $k => $v)
{
$dom->setAttributeNS($ns, $k, $v);
}
return $this;
}
/**
* Return the content of current node as a string
*
* Roughly emulates the innerHTML property found in browsers, although it is not meant to
* perfectly match any specific implementation.
*
* @todo Write a test for HTML entities that can't be represented in the document's encoding
*
* @return string Content of current node
*/
public function innerHTML()
{
$dom = dom_import_simplexml($this);
$doc = $dom->ownerDocument;
$html = '';
foreach ($dom->childNodes as $child)
{
$html .= ($child instanceof DOMText) ? $child->textContent : $doc->saveXML($child);
}
return $html;
}
/**
* Return the XML content of current node as a string
*
* @return string Content of current node
*/
public function innerXML()
{
$xml = $this->outerXML();
$pos = 1 + strpos($xml, '>');
$len = strrpos($xml, '<') - $pos;
return substr($xml, $pos, $len);
}
/**
* Return the XML representing this node and its child nodes
*
* NOTE: unlike asXML() it doesn't return the XML prolog
*
* @return string Content of current node
*/
public function outerXML()
{
$dom = dom_import_simplexml($this);
return $dom->ownerDocument->saveXML($dom);
}
/**
* Return all elements with the given class name
*
* Should work like DOM0's method
*
* @param string $class Class name
* @return array Array of SimpleDOM nodes
*/
public function getElementsByClassName($class)
{
if (strpos($class, '"') !== false
|| strpos($class, "'") !== false)
{
return array();
}
$xpath = './/*[contains(concat(" ", @class, " "), " ' . htmlspecialchars($class) . ' ")]';
return $this->xpath($xpath);
}
/**
* Test whether current node has given class
*
* @param string $class Class name
* @return bool
*/
public function hasClass($class)
{
return in_array($class, explode(' ', $this['class']));
}
/**
* Add given class to current node
*
* @param string $class Class name
* @return SimpleDOM Current node
*/
public function addClass($class)
{
if (!$this->hasClass($class))
{
$current = (string) $this['class'];
if ($current !== ''
&& substr($current, -1) !== ' ')
{
$this['class'] .= ' ';
}
$this['class'] .= $class;
}
return $this;
}
/**
* Remove given class from current node
*
* @param string $class Class name
* @return SimpleDOM Current node
*/
public function removeClass($class)
{
while ($this->hasClass($class))
{
$this['class'] = substr(str_replace(' ' . $class . ' ', ' ', ' ' . $this['class'] . ' '), 1, -1);
}
return $this;
}
//=================================
// Utilities
//=================================
/**
* Return the current element as a DOMElement
*
* @return DOMElement
*/
public function asDOM()
{
return dom_import_simplexml($this);
}
/**
* Return the current node slightly prettified
*
* Elements will be indented, empty elements will be minified. The result isn't mean to be
* perfect, I'm sure there are better prettifiers out there.
*
* @param string $filepath If set, save the result to this file
* @return mixed If $filepath is set, will return TRUE if the file was
* succesfully written or FALSE otherwise. If $filepath isn't set,
* it returns the result as a string
*/
public function asPrettyXML($filepath = null)
{
/**
* Dump and reload this node's XML with LIBXML_NOBLANKS.
*
* Also import it as a DOMDocument because some older of XSLTProcessor rejected
* SimpleXMLElement as a source.
*/
$xml = dom_import_simplexml(new SimpleXMLElement(
$this->asXML()
));
$xsl = new DOMDocument;
$xsl->loadXML(
'<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:template match="text()">
<!-- remove everything that contains only whitespace, with at least one LF -->
<xsl:if test="not(normalize-space(.) = \'\' and contains(., \' \'))">
<xsl:value-of select="."/>
</xsl:if>
</xsl:template>
<xsl:template match="node()">
<xsl:copy>
<xsl:copy-of select="@*" />
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>');
$xslt = new XSLTProcessor;
$xslt->importStylesheet($xsl);
$result = trim($xslt->transformToXML($xml));
if (isset($filepath))
{
return (bool) file_put_contents($filepath, $result);
}
return $result;
}
/**
* Transform current node and return the result
*
* Will take advantage of {@link http://pecl.php.net/package/xslcache PECL's xslcache}
* if available
*
* @param string $filepath Path to stylesheet
* @param bool $use_xslcache If TRUE, use the XSL Cache extension if available
* @return string Result
*/
public function XSLT($filepath, $use_xslcache = true)
{
if ($use_xslcache && extension_loaded('xslcache'))
{
$xslt = new XSLTCache;
$xslt->importStylesheet($filepath);
}
else
{
$xsl = new DOMDocument;
$xsl->load($filepath);
$xslt = new XSLTProcessor;
$xslt->importStylesheet($xsl);
}
return $xslt->transformToXML(dom_import_simplexml($this));
}
/**
* Run an XPath query and sort the result
*
* This method accepts any number of arguments in a way similar to {@link
* http://docs.php.net/manual/en/function.array-multisort.php array_multisort()}
*
* <code>
* // Retrieve all <x/> nodes, sorted by @foo ascending, @bar descending
* $root->sortedXPath('//x', '@foo', '@bar', SORT_DESC);
*
* // Same, but sort @foo numerically and @bar as strings
* $root->sortedXPath('//x', '@foo', SORT_NUMERIC, '@bar', SORT_STRING, SORT_DESC);
* </code>
*
* @param string $xpath XPath expression
* @return void
*/
public function sortedXPath($xpath)
{
$nodes = $this->xpath($xpath);
$args = func_get_args();
$args[0] =& $nodes;
call_user_func_array(array(get_class($this), 'sort'), $args);
return $nodes;
}
/**
* Sort this node's children
*
* ATTENTION: text nodes are not supported. If current node has text nodes, they may be lost in
* the process
*
* @return SimpleDOM This node
*/
public function sortChildren()
{
$nodes = $this->removeNodes('*');
$args = func_get_args();
array_unshift($args, null);
$args[0] =& $nodes;
call_user_func_array(array(get_class($this), 'sort'), $args);
foreach ($nodes as $node)
{
$this->appendChild($node);
}
return $this;
}
/**
* Sort an array of nodes
*
* Note that nodes are sorted in place, nothing is returned
*
* @see sortedXPath
*
* @param array &$nodes Array of SimpleXMLElement
* @return void
*/
static public function sort(array &$nodes)
{
$args = func_get_args();
unset($args[0]);
$sort = array();
$tmp = array();
foreach ($args as $k => $arg)
{
if (is_string($arg))
{
$tmp[$k] = array();
if (preg_match('#^@?[a-z_0-9]+$#Di', $arg))
{
if ($arg[0] === '@')
{
$name = substr($arg, 1);
foreach ($nodes as $node)
{
$tmp[$k][] = (string) $node[$name];
}
}
else
{
foreach ($nodes as $node)
{
$tmp[$k][] = (string) $node->$arg;
}
}
}
elseif (preg_match('#^current\\(\\)|text\\(\\)|\\.$#i', $arg))
{
/**
* If the XPath is current() or text() or . we use this node's textContent
*/
foreach ($nodes as $node)
{
$tmp[$k][] = dom_import_simplexml($node)->textContent;
}
}
else
{
foreach ($nodes as $node)
{
$_nodes = $node->xpath($arg);
$tmp[$k][] = (empty($_nodes)) ? '' : (string) $_nodes[0];
}
}
}
else
{
$tmp[$k] = $arg;
}
/**
* array_multisort() wants everything to be passed as reference so we have to cheat
*/
$sort[] =& $tmp[$k];
}
$sort[] =& $nodes;
call_user_func_array('array_multisort', $sort);
}