这是 XML 文件内容:
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url id="first_url">
<loc>http://example.com</loc>
<lastmod>2014-05-21</lastmod>
</url>
</urlset>
PHP 代码如下:
<?php
$dom = new DOMDocument('1.0', 'utf-8');
$dom->Load('sitemap.xml');
$xpath = new DOMXPath($dom);
$tags = $xpath->query('//url[@id="first_url"]');
foreach($tags as $tag)
print $tag->getAttribute("id")."<br/>";
?>
此代码无效。但是,如果我从文件中删除 xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
,它就可以工作。为什么会这样?谢谢!
最佳答案
是因为命名空间。您可以通过以下方式忽略 namespace :
Xpath 1.0:
//*[local-name()="url"][@id="first_url"]
Xpath 2.0:
//*:url[@id="first_url"]
关于php - 将 xPath 用于 sitemap.xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23783439/