PHP xpath 问题 ->item(0)->nodeValue

标签 php xml xpath xmlnode

基于以下XML我想检索某个节点(ID)的产品名称和图像

<?xml version="1.0" encoding="utf-8"?>
<clients>
    <client id="A">
        <product>Name of product A</product>
        <image>Product image name A</image>
    </client>
    <client id="B">
        <product>Name of product B</product>
        <image>Product image name B</image>
    </client>
</clients>

这是 PHP 代码:

$doc      = DOMDocument::load('clients.xml');
$xpath    = new DOMXPath($doc);
$query    = '//client[@id="A"]'; 
$info = $xpath->query($query);

如果我执行 $info->item(0)->nodeValue 我会同时获取这两个信息,而不是单独获取:

Name of product A
Product image name A

但我想根据客户端ID获取->product->nodeValue和image->nodeValue。 我怎样才能做到这一点?例如,执行 $info->item(0)->product->nodeValue 不起作用。

->item(0)->nodeValue 给出该特定项目内的所有内容(在本例中为 0)

最佳答案

您使用 XPath 来获取节点。 XPath 位置路径的结果是节点列表。 ->item(0) 返回此列表中的第一个节点。这是 client 元素节点。

调用 DOMElement:$nodeValue 始终以字符串形式返回所有后代文本节点。在您的情况下,是 product 内的文本节点和 image 元素节点。

如果您想要单独获取值,您将需要获取子节点。

$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXpath($dom);

foreach ($xpath->evaluate('//client[@id="A"]/*[self::product or self::image]') as $child) {
    echo $child->localName, ': ', $child->nodeValue, "\n";
}

输出:

product: Name of product A
image: Product image name A

关于PHP xpath 问题 ->item(0)->nodeValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26985755/

相关文章:

javascript - 使用ajax或jsonp检索php源代码

PHP/MySQL 错误

php - MySQL - 计算问卷答案。

php - foreach数组函数存储在一个变量中?

javascript - jQuery - 复选框选择一行中的所有内容或具有相似名称和 ID

html - XPath根据标签选择表格单元格?

xml - XPath 选择存在具有给定属性值的子节点的节点

html - XPath 查询 : get attribute href from a tag

xml - Golang Xml Unmarshal,没有值(value)

用于提取链接的 HTML Treebuilder XPath