Reputation: 49
<Node name="node1">
<x x="x"/>
<x x="xxx"/>
</Node>
<Node name="node2">
<x x="xx"/>
<x x="xxxx"/>
</Node>
Okay, this is an XML sample:
I call its content using simplexml_load_file
and if i wanna call a specific node content it should be :
$xml = simplexml_load_file('file.xml');
$contents = $xml->node1
and to call node object
$contents = $xml->node1->x
Seems fine till now, the question is, how to call object "x" without mentioning node name
you noticed the sample i added above it has 2 nodes
to call x from it i should mention nodename then x
i want to call all "x" from the whole XML
how is it possible?
Upvotes: 0
Views: 194
Reputation: 3661
SimpleXMLElement::xpath() will do the trick when you don't have namespaces to worry about. If you do have namespaces... you'll need SimpleXMLElement::registerXPathNamespace().
<?php
$xml = <<<EOT
<?xml version="1.0" encoding="UTF-8" ?>
<root>
<Node name="node1">
<x x="x"/>
<x x="xxx"/>
</Node>
<Node name="node2">
<x x="xx"/>
<x x="xxxx"/>
</Node>
</root>
EOT;
// Original question
$s = new SimpleXMLElement($xml);
$r = $s->xpath('//Node/x');
var_dump($r);
// Something about names
$r2 = $s->xpath('Node[@name]');
$names = array();
foreach($r2 as $elem){
$names[] = "{$elem['name']}";
}
var_dump($names);
// RoseWarad's answer (more efficient than "something about names")
$r3 = $s->xpath('*/@name');
var_dump($r3);
?>
Upvotes: 1