简体   繁体   中英

PHP XML Not loading using XPath

I'm loading a XML file as follows:

$places=simplexml_load_file("http://www.43places.com/service/search_places?api_key=1234&q=america");
$allPlaces=$places->xpath('//place');
foreach($allPlaces as $title)
{
    echo "a";
}

Simply to test it, the file is correctly loading, you can see the XML file here .

Any idea why it is not looping??

I'm not sure why XPath wouldn't work but, based on the XML structure I see there, you really don't need XPath. SimpleXMLElements can be a little bearish but it would be extremely easy to use this alternative loop structure:

foreach( $places->place as $place )
{
    echo "a";
}

And you won't need the overhead of an xpath query at all; the structure you want is already right there.

It's not looping because it does not return any nodes. So why is that?

Technically, the <place> element is within a namespace of it's own: http://www.43places.com/xml/2005/rc# , so place is only the so called local name of the element and not it's full name. Xpath does not accept full names but you can register a namespace for xpath operations with a name (prefix) of your choice and then use it in the xpath query:

$places->registerXPathNamespace("a", "http://www.43places.com/xml/2005/rc#");
$allPlaces = $places->xpath('//a:place');

This query now selects the 20 or so place elements you're looking for.

See as well: SimpleXML: Working with XML containing namespaces .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM