PHP XML DOM 解析问题


PHP XML DOM parsing issue

我在xml解析方面有点新,我试图弄清楚这段代码有什么问题,为什么它拒绝显示任何结果?

//php code
    $file=file_get_contents("http://".$_SERVER["HTTP_HOST"]."/sitemap.xml");
    $dom = new DOMDocument();
    $dom->loadXML($file);
    $xmlPath = new DOMXPath($dom);
    $arrNodes = $xmlPath->query('//loc');
    foreach($arrNodes as $arrNode){
        echo $arrNode->nodeValue;
    }

//sitemap.xml
    <url>
    <loc>http://calculosophia.com/</loc>
    </url>
    <url>
      <loc>http://calculosophia.com/finance/compound-interest-calculator</loc>
    </url>

我可以看到该文件已成功检索,但是当var转储$arrNodes时,它给了我object(DOMNodeList)[170]我不知道该怎么做

$arrNodes = $xmlPath->query('//loc');

此行返回一个包含 0 个元素的 DOMNodeList。 这是因为根元素 ( <urlset> ) 正在声明一个命名空间(xmlns 属性)。 XPath 需要先了解此命名空间,然后才能使用它来查询文件。

$xmlPath = new DOMXPath($dom);
// The 1st parameter is just name, it can be whatever you want
// The 2nd parameter is the namespace URL (the value of the "xmlns" attribute)
$xmlPath->registerNamespace('sitemap', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$arrNodes = $xmlPath->query('//sitemap:loc');