note 40834 added to function.xpath-eval

From: Date: Tue, 16 Mar 2004 13:42:28 +0000
Subject: note 40834 added to function.xpath-eval
Groups: php.notes 
Request: Send a blank email to php-notes+get-66911@lists.php.net to get a copy of this message
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 ) ) ---- Manual Page -- http://www.php.net/manual/en/function.xpath-eval.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40834 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40834&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40834&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#66911) next »