gpt4 book ai didi

php - XPATH - 获取返回的单个值而不是数组 php

转载 作者:行者123 更新时间:2023-12-03 16:21:57 25 4
gpt4 key购买 nike

我在 PHP 中使用 Xpath - 我知道我的查询将返回 0 或 1 个结果。

如果返回 1 个结果,我不希望它作为一个数组 - 这就是现在返回的内容。我只是想要这个值而不必访问 [0]结果的元素并转换为字符串。

这可能吗?

最佳答案

If 1 result is returned I dont want it as an array - which is what is returned. I simply want the value without having to access the [0] element of the result and cast to a string.



XPath's string function 可以做到这一点

A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.



DOMXPath's evaluate 方法:

Returns a typed result if possible or a DOMNodeList containing all nodes matching the given XPath expression.



示例:
$dom = new DOMDocument;
$dom->loadXML('<root foo="bar"/>');
$xp = new DOMXPath($dom);
var_dump($xp->evaluate('string(/root/@foo)')); // string(3) "bar"

If there was a built in xpath way of grabbing the first and only the first node value then that would be much more preferable over writing a function to do it



您可以使用 position function :

The position function returns a number equal to the context position from the expression evaluation context.



示例:
$dom = new DOMDocument;
$dom->loadXML('<root><foo xml:id="f1"/><foo xml:id="f2"/></root>');
$xp = new DOMXPath($dom);
var_dump($xp->evaluate('string(/root/foo[position() = 1]/@xml:id)')); // string(2) "f1"

abbreviated syntax
$dom = new DOMDocument;
$dom->loadXML('<root><foo xml:id="f1"/><foo xml:id="f2"/></root>');
$xp = new DOMXPath($dom);
var_dump($xp->evaluate('string(/root/foo[1]/@xml:id)')); // string(2) "f1"

请注意,当使用//使用位置函数查询后代时,由于表达式的评估方式,可能会产生多个结果。

关于php - XPATH - 获取返回的单个值而不是数组 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7464092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com