note 40834 deleted from function.xpath-eval by sobak
| From: | sobak@php.net | Date: | Tue, 22 Nov 2016 03:41:47 +0000 |
| Subject: | note 40834 deleted from function.xpath-eval by sobak | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-207413@lists.php.net to get a copy of this message | ||
Note Submitter: patrikG at home dot net
----
Just an example of how to grab XML attributes with xpath - which took me a while to figure out.
I'm filtering the returned object function node_content() which is a somewhat quick'n
dirty solution, but I don't always need XML's child-parent relationships.
<?php
$xml='<MY_SERVICE>
<MERCHANDISE>
<SERVICE TYPE="books">
<NAME>Ulysses</NAME>
</SERVICE>
<SERVICE TYPE="books">
<NAME>The Poisonwood Bible</NAME>
</SERVICE>
<SERVICE TYPE="cars">
<NAME>Van</NAME>
</SERVICE>
<SERVICE TYPE="vehicle sans wheels">
<NAME>UFO</NAME>
</SERVICE>
</MERCHANDISE>
</MY_SERVICE>';
echo
"<h4>XML</h4><xmp>";print_r(parse_XML($xml));echo"</xmp>";
function node_content($node,$attribute="content"){
foreach($node->nodeset as $content){
$return[] = $content->{$attribute};
}
return $return;
}
function parse_XML($xml){
//needs PHP's xPath extension installed
$dom =domxml_open_mem($xml);
$calcX = &$dom->xpath_new_context();
$xml_parsed["merchandise"]=node_content(
$calcX->xpath_eval("//MERCHANDISE/SERVICE/NAME/text()")
);
$xml_parsed["service"]=node_content(
$calcX->xpath_eval("//MERCHANDISE/SERVICE/attribute::TYPE",$calcX)
,"value");
return $xml_parsed;
}
?>
The code above returns:
XML
Array
(
[merchandise] => Array
(
[0] => Ulysses
[1] => The Poisonwood Bible
[2] => Van
[3] => UFO
)
[service] => Array
(
[0] => books
[1] => books
[2] => cars
[3] => vehicle sans wheels
)
)