【问题标题】:Parsing XML with multiple namespaces in PHP在 PHP 中使用多个名称空间解析 XML
【发布时间】: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-&gt;childrenDOMElement::getElementsByTagNameNS ( string $namespaceURI , string $localName )(这将是由 atomentry 定义的 uri,没有 atom: 前缀),拜托,只是为了它,在 SO 上找到数百个类似问题之一。从长远来看,这不是一个新问题。
  • 只需$doc-&gt;getElementsByTagName("entry"); 手册中的关键字是本地名称

标签: php xml-namespaces


【解决方案1】:

我只想发布这个可怕问题的答案。对不起。

命名空间与 DOM 无关——我只是没有从元素中获取 nodeValue。

$doc = new DOMDocument();
$doc->load($url);
$feed = $doc->getElementsByTagName("entry");
foreach($feed as $entry) {
    $id = $entry->getElementsByTagName("id")->item(0)->nodeValue;
    echo $id;
    $id = $entry->getElementsByTagName("othervalue")->item(0)->nodeValue;
    echo $othervalue;
}

【讨论】:

    【解决方案2】:

    您需要注册您的名称空间。否则 simplexml 将忽略它们。 这段代码是我从 PHP 手册中得到的,我在自己的项目中使用过

    $xmlsimple = simplexml_load_string('YOUR XML'); 
    $namespaces = $xmlsimple->getNamespaces(true);
    $extensions = array_keys($namespaces);
    
    foreach ($extensions as  $extension )
    {
        $xmlsimple->registerXPathNamespace($extension,$namespaces[$extension]);
    }
    

    之后你在 $xmlsimple 上使用 xpath

    【讨论】:

      猜你喜欢
      • 2016-09-22
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 2012-06-11
      • 2012-07-23
      • 1970-01-01
      • 2019-07-26
      • 2013-04-30
      相关资源
      最近更新 更多