views:

144

answers:

1

Hi Guys,

I have an xml file that I want to store a node's rank attribute in a variable.

I tried:

echo $var = $xmlobj->xpath("//Listing[@rank]");

to no avail, it just prints ArrayArray.

How can this be done?

if($xmlobj = simplexml_load_string(file_get_contents($xml_feed)))
      {
      foreach($xmlobj as $listing)
      {

         // echo 'Session ID: ' . $sessionId = $listing->sessionId . '<br />';
         // echo 'Result Set: ' . $ResultSet = $listing->ResultSet . '<br />';

         print_r($xmlobj->xpath("//Listing[@rank]"));

         // $result = $xmlobj->xpath("/page/");
         // print_r($result);

            }
      }

Henrik's suggestion:

foreach($xmlobj as $listing)
{
      $var = $xmlobj->xpath("//Listing[@rank]");

      foreach ($var as $xmlElement) 
      {
            echo (string)$xmlElement;
      }
}

Here you go

<page>
   <ResultSet id="adListings" numResults="3">
      <Listing rank="1" title="Reliable Local Moving Company" description="TEST." siteHost="www.example.com">
      </Listing>
+2  A: 

Edit after playing around with the posted example xml:

  • My initial answer was somewhat off track - casting to string would give you the inner text of the selected elements, if they have one (not the case here)
  • "//Listing[@rank]" selects all 'Listing' Elements that have a 'rank' attribute. If you want to select the attributes themselves, use "//Listing/@rank"
  • To output an attribute, use the SimpleXMLElement with array syntax: $xmlElement['rank']

So in your case:

foreach($xmlobj as $listing)
{
    $var = $xmlobj->xpath("//Listing/@rank");
    foreach ($var as $xmlElement) 
    {
      echo $xmlElement['rank'];
    }
}

or

foreach($xmlobj as $listing)
{
    $var = $xmlobj->xpath("//Listing[@rank]");
    foreach ($var as $xmlElement) 
    {
      echo $xmlElement['rank'];
      echo $xmlElement['title']; // Added to demonstrate difference
    }
}

should work.

In the first case, the $xmlElement would only contain the 'rank' attribute while in the second, it would contain the complete 'Listing' element (hence allowing the title output).

Henrik Opel
Thanks for the reply Henrik. Unfortunately it doesn't work, My implementation of your code is above?
Keith Donegan
Hmm, strange - what does it print?
Henrik Opel
Just a blank screen and no errors
Keith Donegan
Ok, that would hint on the xpath not actually matching anything - could you post an example of your xml?
Henrik Opel
Thanks for your help, posted above
Keith Donegan
Ok, took a while - I seem to have forgotten some basics since I last used simpleXML ;)
Henrik Opel
Henrik, thank you so much mate, that is perfect! - I appreciate all your help, all the best, Keith
Keith Donegan