Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 简单的xpath查询,但没有结果_Php_Xpath - Fatal编程技术网

Php 简单的xpath查询,但没有结果

Php 简单的xpath查询,但没有结果,php,xpath,Php,Xpath,正在尝试从xml获取所有URL值 我有数百个条目的格式,例如,此条目16: <?xml version="1.0" encoding="utf-8" ?> <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <entries> <entry id="16"> <revision number="1" status="accepted" wordcla

正在尝试从xml获取所有URL值

我有数百个
条目
的格式,例如,此条目
16

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <entries>
   <entry id="16">
      <revision number="1" status="accepted" wordclass="v" nounclasses="" unverified="false"></revision>
      <media type="audio" url="http://website.com/file/65.mp3" />
      </entry>
   <entry id="17">
      ....
   </entry>
</entries>
</root>

correc对此有何疑问?最好只获取
url
值。

您的查询可能会返回正确的元素,但默认情况下会提供媒体标签的内容(在您的情况下,该标签是空的,因为标签是自动关闭的)

要获取标记的
url
属性,应使用
getAttribute()
,例如:

$entries = $xpath->query('//root/entries/entry/media');
foreach($entries as $entry) { 
  print $entry->getAttribute("url")."<br/>";
}
$entries=$xpath->query('//root/entries/entry/media');
foreach($entries作为$entry){
打印$entry->getAttribute(“url”)。“
”; }
或者,您应该改为使用xpath查询属性并读取其值:

$urlAttributes = $xpath->query('//root/entries/entry/media/@url');
                                                          #####
foreach ($urlAttributes as $urlAttribute)
{ 
    echo $urlAttribute->value, "<br/>\n";
                        #####
}
$urldattributes=$xpath->query('//root/entries/entry/media/@url');
#####
foreach($urldattributes作为$urldattribute)
{ 
echo$urldattribute->value“
\n”; ##### }
见:

价值观


属性的值


我会用SimpleXML实现这一点,实际上:

$file  = 'data.xml';
$xpath = '//root/entries/entry/media/@url';

$xml  = simplexml_load_file($file);
$urls = array();

if ($xml) {
    $urls = array_map('strval', $xml->xpath($xpath));
}

这将在
$url
数组中以字符串形式提供所有URL。如果加载XML文件时出错,则数组为空。

谢谢。现在它起作用了。当我删除这个xmlns=somepage时,我删除了这个
。成功了。在没有输出之前。或者使用
'//root/entries/entry/media/@url'
作为XPath直接获取
DomAttr
节点。
$file  = 'data.xml';
$xpath = '//root/entries/entry/media/@url';

$xml  = simplexml_load_file($file);
$urls = array();

if ($xml) {
    $urls = array_map('strval', $xml->xpath($xpath));
}