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>
Edit after playing around with the posted example xml:
"//Listing[@rank]"selects all ‘Listing’ Elements that have a ‘rank’ attribute. If you want to select the attributes themselves, use"//Listing/@rank"$xmlElement['rank']So in your case:
or
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).