0
votes

I have a test file where I'm trying to parse an xml string using SimpleXML's xpath method.

When I try to access a nodes values directly using xpath I get empty output, but when I use xpath to grab the elements and then loop through them it works fine.

When I look at the documentation, it seems like my syntax should work. Is there something I'm missing?

<?php

$xmlstring = '<?xml version="1.0" encoding="iso-8859-1"?>
<users>
  <user>
    <firstname>Sheila</firstname>
    <surname>Green</surname>
    <address>2 Good St</address>
    <city>Campbelltown</city>
    <country>Australia</country>
    <contact>
      <phone type="mobile">1234 1234</phone>
      <url>http://example.com</url>
      <email>[email protected]</email>
    </contact>
  </user>
  <user>
    <firstname>Bruce</firstname>
    <surname>Smith</surname>
    <address>1 Yakka St</address>
    <city>Meekatharra</city>
    <country>Australia</country>
    <contact>
      <phone type="landline">4444 4444</phone>
      <url>http://yakka.example.com</url>
      <email>[email protected]</email>
    </contact>
  </user>
</users>';


// Start parsing
if(!$xml = simplexml_load_string($xmlstring)){
    echo "Error loading string ";
} else {
    echo "<pre>";

    // Print all firstname values directly from xpath
    // This outputs the elements, but the values are blank
    print_r($xml->xpath("/users/user/firstname"));

    // Set a variable with all of the user elements and then loop through and print firstname values
    // This DOES output the values
    $users = $xml->xpath("/users/user");
    foreach($users as $user){
        echo $user->firstname;
    }

    // Find all firstname values by tag
    // This does not output the values 
    print_r($xml->xpath("//firstname"));
    echo "</pre>";
}
1
Bit confused. Results are returned for all three of your queries. Are you just having trouble getting the data out? - rjdown

1 Answers

0
votes

As per the manual http://uk1.php.net/manual/en/simplexmlelement.xpath.php

The xpath method searches the SimpleXML node for children matching the XPath path.

In your first and third examples, you are being returned objects containing an array of the node's value, rather than the node itself. So you aren't going to be able to do e.g.

$results = $xml->xpath("//firstname");
foreach ($results as $result) {
    echo $result->firstname;
}

Instead you can just echo out the value directly. Well, almost directly (they are still simplexml objects after all)...

$results = $xml->xpath("//firstname");
foreach ($results as $result) {
    echo $result->__toString();
}