【发布时间】:2012-06-14 23:18:39
【问题描述】:
我有以下格式的 XML,我想用 PHP 解析(我无法更改 XML 的格式)。 SimpleXML 和 DOM 似乎都不能处理不同的命名空间——谁能给我示例代码?下面的代码没有给出任何结果。
<atom:feed>
<atom:entry>
<atom:id />
<otherns:othervalue />
</atom:entry>
<atom:entry>
<atom:id />
<otherns:othervalue />
</atom:entry>
</atom:feed>
$doc = new DOMDocument();
$doc->load($url);
$entries = $doc->getElementsByTagName("atom:entry");
foreach($entries as $entry) {
$id = $entry->getElementsByTagName("atom:id");
echo $id;
$othervalue = $entry->getElementsByTagName("otherns:othervalue");
echo $othervalue;
}
【问题讨论】:
-
SimpleXMLElement->children或DOMElement::getElementsByTagNameNS ( string $namespaceURI , string $localName )(这将是由atom和entry定义的 uri,没有atom:前缀),拜托,只是为了它,在 SO 上找到数百个类似问题之一。从长远来看,这不是一个新问题。 -
只需
$doc->getElementsByTagName("entry");手册中的关键字是本地名称。
标签: php xml-namespaces