0

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

hakre
  • 193,403
  • 52
  • 435
  • 836
Noor
  • 19,638
  • 38
  • 136
  • 254

2 Answers2

3

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.

Kevin Nielsen
  • 4,413
  • 21
  • 26
2

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.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836