SimpleXMLElement
has a getName()
method:
echo $node->getName();
Assumption: $node
is a SimpleXMLElement object.
Question
For example I have 2 types of nodes in my xml file:
1) <book>
2) <author>
A variable named $node points to specific node(of unknown type). How can I access this node's name? It must be something like this:
if($node->name()=="book")
process_book($node);
else
process_author;
Solution
SimpleXMLElement
has a getName()
method:
echo $node->getName();
Assumption: $node
is a SimpleXMLElement object.
OTHER TIPS
I may be missing something, but here is a simlpe solution. Change simplexml_load_string
to simplexml_load_file
if your using a file.
$xml_string = <<<XML
<root>
<item>
<book>Book 1</book>
<author>Author 1</author>
</item>
<item>
<book>Book 2</book>
<author>Author 2</author>
</item>
<item>
<book>Book 3</book>
<author>Author 3</author>
</item>
</root>
XML;
$xml = simplexml_load_string($xml_string);
foreach($xml->item as $node){
if(isset($node->book)){
process_book($node);
}
}