1

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;
bukbukXiu
  • 13
  • 5

2 Answers2

0

SimpleXMLElement has a getName() method:

echo $node->getName();

Assumption: $node is a SimpleXMLElement object.

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
0

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);
    }
}
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • In your case, $node points to the PARENT of the node that you process. That's not what I need, but thanks. – bukbukXiu Nov 16 '12 at 17:34