简体   繁体   中英

How to get the name of a node in a xml file using xpath/php?

I have a large xml file and I need to print every entry with a specific namespace and the name of its node (with PHP).

For example, given the following xml structure:

    <file>
        <myNamespace:node1>entry1</myNamespace:node1>
        <myNamespace:node2>entry2</myNamespace:node2>
        ... [any other nodes here] ...
    </file>

I want to print a tuple of [node1, entry1], [node2, entry2] and so on for every node in the xml file with the myNamespace namespace. The Problem is, I don't know how to get the name of the nodes (the 'node1', 'node2', ...), I only get the entries. For now I'm using this code:

    foreach($xml->xpath('myNamespace:*') as $value) {
        echo $value.'<br />';
    }

I read something about name() and local-name() function, but I can't get it to work :( Thank you for helping me!

You should use getName() - try something like:

foreach($xml->xpath('myNamespace:*') as $value) { 
    echo $value->getName().'='.$value.'<br />'; 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM