|   | php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login | 
| 
  [2010-08-31 11:24 UTC] ivan dot enderlin at hoa-project dot net
 Description:
------------
SimpleXML misses a XPath function which is processing-instruction(). This last one enables to reach/select PIs along the XML document.
Test script:
---------------
<?php
$xml = '<?xml version="1.0" encoding="utf-8"?>' . "\n\n" .
       '<foo>' . "\n" .
       '  <bar>Gordon</bar>' . "\n" .
       '  <bar><![CDATA[Gordon]]></bar>' . "\n" .
       '  <bar><?baz href="ftw" ?></bar>' . "\n" .
       '</foo>';
$sxe = simplexml_load_string($xml);
var_dump(
    $sxe->xpath('//bar')
);
var_dump(
    $sxe->xpath('//processing-instruction(\'baz\')')
);
Expected result:
----------------
//bar
array(3) {
  [0]=>
  object(SimpleXMLElement)#2 (1) {
    [0]=>
    string(6) "Gordon"
  }
  [1]=>
  object(SimpleXMLElement)#3 (0) {
  }
  [2]=>
  object(SimpleXMLElement)#4 (1) {
    ["baz"]=>
    object(SimpleXMLElement)#5 (0) {
    }
  }
}
//processing-instruction('baz')
array(1) {
  [2]=>
  object(SimpleXMLElement)#6 (1) {
    …
  }
}
Actual result:
--------------
//bar
array(3) {
  [0]=>
  object(SimpleXMLElement)#2 (1) {
    [0]=>
    string(6) "Gordon"
  }
  [1]=>
  object(SimpleXMLElement)#3 (0) {
  }
  [2]=>
  object(SimpleXMLElement)#4 (1) {
    ["baz"]=>
    object(SimpleXMLElement)#5 (0) {
    }
  }
}
//processing-instruction('baz')
array(0) {
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits             | |||||||||||||||||||||||||||||||||||||
|  Copyright © 2001-2025 The PHP Group All rights reserved. | Last updated: Fri Oct 31 15:00:01 2025 UTC | 
I forget to notice that DOMXPath support this function. If we take the first code example: $doc = dom_import_simplexml($sxe)->ownerDocument; $xpath = new DOMXPath($doc); $e = $xpath->query('//processing-instruction(\'baz\')'); var_dump($e, $e->length, $e->item(0)->data); It will output: object(DOMNodeList)#8 (0) { } int(1) string(11) "href="ftw" " That's what we expected! But I think that SimpleXML does not simply support PI. Maybe you noticed that when outputing //bar, in the 2 offset, we have “baz”. Well, try to use it: $handle = $sxe->xpath('//bar'); var_dump( dom_import_simplexml($handle[2]) ->childNodes ->item(0) ->data ); It will output: string(11) "href="ftw" " We must use the DOM API to reach PI data. Conclusion: • processing-instruction() works with DOMXpath, not with SimpleXML. • PIs appear in the DOM and the SimpleXML tree. • PIs are usable only with the DOM API.