使用 PHP DOMDocument 从具有带冒号的命名空间的 xml 节点获取值
Get value from xml node with namespace with colon using PHP DOMDocument
我正在使用 DOMDocument class 解析 xml 文档。首先,我使用 $xml->getElementsByTagName('item')
方法选择了名称为 'item' 的所有节点。我的示例 xml 文件如下所示:
<item>
<title>...</link>
<description>...</description>
<pubDate>...</pubDate>
<ns:author>...</dc:creator>
</item>
但是我的问题是从带有冒号的命名空间名称的嵌套标记中获取值。我使用 $node->getElementsByTagName('description')->item(0)->nodeValue
从 foreach
中没有名称空间的节点获取值,并且没有错误。
我还找到了方法 getElementsByTagNameNs() 来获取带有它的命名空间的节点。但是,当我尝试像以前没有名称空间的节点一样获取 nodeValue 时,我得到 "PHP Notice: Trying to get property of non-object"。我认为这很奇怪,因为 getElementsByTagNameNs()->item(0)
returns object DOMElement.
你知道如何从具有命名空间的节点获取值吗,在本例中是 <ns:author></dc:creator>
元素?
由于您提供的文档片段不完整甚至无效,我不得不进行一些更改。你说你想要 <ns:author>...</dc:creator>
的值,它不是一个有效的元素,因为打开和关闭名称在名称和命名空间中是不同的,你会期望像 <ns:author>...</ns:author>
作为如何从命名空间获取值的示例(使用对 XML 的一些更正和一些猜测的更改)...
$xml = <<<XML
<?xml version="1.0"?>
<items xmlns:ns="http://some.url">
<item>
<title>title</title>
<description>Descr.</description>
<pubDate>1/1/1970</pubDate>
<ns:author>author1</ns:author>
</item>
</items>
XML;
$dom = new DOMDocument( '1.0', 'utf-8' );
$dom->loadXML($xml);
$items = $dom->getElementsByTagName('item');
foreach ( $items as $item ) {
$author = $item->getElementsByTagNameNS("http://some.url", "*")->item(0)->nodeValue;
echo "Author = ".$author.PHP_EOL;
}
在 getElementsByTagNameNS()
中,您需要为此命名空间输入正确的 URL,它应该在源文档中。
这输出...
Author = author1
我正在使用 DOMDocument class 解析 xml 文档。首先,我使用 $xml->getElementsByTagName('item')
方法选择了名称为 'item' 的所有节点。我的示例 xml 文件如下所示:
<item>
<title>...</link>
<description>...</description>
<pubDate>...</pubDate>
<ns:author>...</dc:creator>
</item>
但是我的问题是从带有冒号的命名空间名称的嵌套标记中获取值。我使用 $node->getElementsByTagName('description')->item(0)->nodeValue
从 foreach
中没有名称空间的节点获取值,并且没有错误。
我还找到了方法 getElementsByTagNameNs() 来获取带有它的命名空间的节点。但是,当我尝试像以前没有名称空间的节点一样获取 nodeValue 时,我得到 "PHP Notice: Trying to get property of non-object"。我认为这很奇怪,因为 getElementsByTagNameNs()->item(0)
returns object DOMElement.
你知道如何从具有命名空间的节点获取值吗,在本例中是 <ns:author></dc:creator>
元素?
由于您提供的文档片段不完整甚至无效,我不得不进行一些更改。你说你想要 <ns:author>...</dc:creator>
的值,它不是一个有效的元素,因为打开和关闭名称在名称和命名空间中是不同的,你会期望像 <ns:author>...</ns:author>
作为如何从命名空间获取值的示例(使用对 XML 的一些更正和一些猜测的更改)...
$xml = <<<XML
<?xml version="1.0"?>
<items xmlns:ns="http://some.url">
<item>
<title>title</title>
<description>Descr.</description>
<pubDate>1/1/1970</pubDate>
<ns:author>author1</ns:author>
</item>
</items>
XML;
$dom = new DOMDocument( '1.0', 'utf-8' );
$dom->loadXML($xml);
$items = $dom->getElementsByTagName('item');
foreach ( $items as $item ) {
$author = $item->getElementsByTagNameNS("http://some.url", "*")->item(0)->nodeValue;
echo "Author = ".$author.PHP_EOL;
}
在 getElementsByTagNameNS()
中,您需要为此命名空间输入正确的 URL,它应该在源文档中。
这输出...
Author = author1