Saturday, 15 September 2012

Get XML element by ID with PHP -



Get XML element by ID with PHP -

i'm having difficulties getting php read xml document. i'm trying echo content each node based on whatever catid i've selected.

xml: text.xml

<root> <category catid='1'> <text id='txt1'><![cdata[ lorem ipsum ]]></text> <text id='txt2'><![cdata[ lorem ipsum ]]></text> <text id='txt3'><![cdata[ lorem ipsum ]]></text> </category> <category catid='2'> <text id='txt1'><![cdata[ lorem ipsum ]]></text> <text id='txt2'><![cdata[ lorem ipsum ]]></text> <text id='txt3'><![cdata[ lorem ipsum ]]></text> </category> </root>

php:

<?php $xml = simplexml_load_file('/path/to/text.xml'); $category = $xml->xpath("//category[@catid='1']/text"); $ids = ['txt1', 'txt2', 'txt3']; foreach($ids $id){ echo $category[$id]; //i'm not quite sure how bit. } ?>

any help appreciated, thanks!

here comes illustration how using dom extension xpath:

$doc = new domdocument(); $doc->loadxml($xml); $selector = new domxpath($doc); $result = $selector->query("//category[@catid='1']"); if($result->length !== 1) { die('bad xml'); } $category = $result->item(0); $ids = array('txt1', 'txt2', 'txt3'); foreach($ids $id){ // note $category sec argument. meaning query // relative category node , not root node $textresult = $selector->query("text[@id='$id']", $category); if($textresult->length < 1) { die('bad xml'); } $text = $textresult->item(0)->nodevalue; echo $text, php_eol; }

php xml

No comments:

Post a Comment