无法获取 XML 的命名空间属性


Can't get out namespace attributes of XML

试图从<af:location>value</af:location>中获取值。首先;是的,我已经搜索了很多关于如何做的答案。在Stackoverflow上阅读了很多问题,并尝试了许多代码。但就是无法让它工作。

不能展示我做过的所有尝试,因为我不记得我尝试过的所有事情。

这是我正在使用的代码的剥离版本:

$xml_dump = Feed::curl_file_get_contents($url);
libxml_use_internal_errors(true);
    if ($xml = simplexml_load_string($xml_dump))
    {
    }

例如,我尝试过:

  • 命名空间参数'af' -> simplexml_load_string($xml_dump, null, 0, 'af', true)
  • $xml->getNamespaces(true)
  • $sxe = new SimpleXMLElement($xml_dump); $namespaces = $sxe->getNamespaces(true);

但它们都不起作用。

$xml_dump包含以下内容:

<?xml version="1.0"?>
<rss version="2.0" xmlns:af="http://www.example.se/rss">
    <channel>
        <title>RSS Title - Example.se</title>
        <link>http://www.example.se</link>
        <description>A description of the site</description>
        <pubDate>Wed, 24 Feb 2016 12:20:03 +0100</pubDate>

                <item>
                     <title>The title</title>
                     <link>http://www.example.se/2.1799db44et3a9800024.html?id=233068</link>
                     <description>A lot of text. A lot of text. A lot of text.</description>
                     <guid isPermaLink="false">example.se:item:233068</guid>
                     <pubDate>Wed, 24 Feb 2016 14:55:34 +0100</pubDate>
                     <af:profession>16/5311/5716</af:profession>
                     <af:location>1/160</af:location>
                </item>
  </channel>
</rss>

解决!

答案是:

$loc = $item->xpath('af:location');
echo $loc[0];

我不得不说,这个问题不清楚。您在问题开头提到了从带有前缀的元素中获取值。但似乎试图在每次尝试的代码中获取命名空间。

"试图从<af:location>value</af:location>中获取价值"

如果您的意思是从上面提到的元素中获取值,那么这是一种可能的方法:

$location = $xml->xpath('//af:location')[0];
echo $location;

输出:

1/160

如果您的意思是通过前缀名称获取命名空间 URI,那么使用 getNamespaces() 是要走的路:

echo $xml->getNamespaces(true)['af'];

输出:

http://www.example.se/rss

我们真的需要一个体面的规范答案,但我要在这里再重复一遍,因为你搜索了但没有找到。答案非常简单:你使用children()方法。

这采用永久标识命名空间的 URI(推荐)或要解析的特定文档中使用的前缀(如果文件是自动生成的,则可能会更改)。

在您的示例中,我们有 xmlns:af="http://www.example.se/rss" ,因此我们可以将该 URI 保存到常量中,以用对我们有意义的内容标识命名空间:

define('XMLNS_RSSAF', 'http://www.example.se/rss');

然后在分析 XML 时,以正常方式遍历到 item 元素:

$xml = simplexml_load_string($xml_dump);
foreach ( $xml->channel->item as $item ) {
    // ...
}

通过指定命名空间,您可以获得 $item 的命名空间子项:

$location = (string) $item->children(XMLNS_RSSAF)->location;