Search code examples
phpxpathsimplexml

XPath in PHP - SimpleXMLElement key numeric instead of textual


I have the following XML saved in $string

<?xml version="1.0" encoding="ISO-8859-1"?>
<users>
  <user id="1">
    <name>Michael Tray</name>
    <account>473.43</account>
  </user>
  <user id="2">
    <name>Sandra Marry</name>
    <account>154.24</account>
  </user>
</users>

I use the following simple XPath expression to get all names

$xml = simplexml_load_string($string);
$result = $xml->xpath("/users/user/name");
echo "<pre>";
print_r($result);
echo "</pre>";

What I get

Array (
    [0] => SimpleXMLElement Object
        (
            [0] => Michael Tray
        )

    [1] => SimpleXMLElement Object
        (
            [0] => Sandra Marry
        )
)

What I want

Array (
    [0] => SimpleXMLElement Object
        (
            [name] => Michael Tray
        )

    [1] => SimpleXMLElement Object
        (
            [name] => Sandra Marry
        )
)

So the SimpleXMLElement key should be a string (tag name) and not a number. How can I do that?


Solution

  • As usual with SimpleXML, print_r is lying to you. The objects don't really have a "key" of 0 at all.

    Each object actually represent a single XML element, and you can access the tag name using getName(), and the string content with a (string) cast, as follows:

    foreach ( $result as $node ) {
        echo 'Name: ', $node->getName(), '; ';
        echo 'Content: ', (string)$node, '<br />';
    }
    

    (The (string) is actually redundant with echo, because it forces things to string anyway, but is important to remember anywhere else to avoid passing around the whole object by mistake.)