简体   繁体   English

不使用XPath加载PHP XML

[英]PHP XML Not loading using XPath

I'm loading a XML file as follows: 我正在加载XML文件,如下所示:

$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 . 简单测试一下,文件已正确加载,您可以在此处查看XML文件。

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. 我不确定为什么XPath无法使用,但是根据我在那里看到的XML结构,您真的不需要XPath。 SimpleXMLElements can be a little bearish but it would be extremely easy to use this alternative loop structure: SimpleXMLElements可能有点看跌,但是使用这种备用循环结构将非常容易:

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

And you won't need the overhead of an xpath query at all; 而且,您根本不需要xpath查询的开销。 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. 从技术上讲, <place>元素位于其自己的命名空间内: http://www.43places.com/xml/2005/rc# : http://www.43places.com/xml/2005/rc# ,因此place只是所谓的元素本地名称 ,而不是全名。 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: Xpath不接受全名,但是您可以使用您选择的名称(前缀)为xpath操作注册一个名称空间,然后在xpath查询中使用它:

$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. 现在,此查询将选择您要查找的20个左右的place元素。

See as well: SimpleXML: Working with XML containing namespaces . 另请参见: SimpleXML:使用包含名称空间的XML

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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