1

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>
4

1 回答 1

2

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).

于 2009-10-01T15:26:46.527 回答