[英]Can't get PHP DOMXpath substring functions to work
Using the following PHP code sample: 使用以下PHP代码示例:
$xml = "<person><name>John-Doe</name></person>";
$doc = new DOMDocument("1.0", "ISO-8859-15");
$xpath = new DOMXpath($doc);
$nodelist = $xpath->query("substring-before(/person/name/text(), '-Doe')");
print "Found " . $nodelist->length . " results.";
I get the output: 我得到输出:
Found 0 results
找到0结果
But when I put the same XML and xpath query into online Xpath testers, I get the expected result, which is "John" 但是当我将相同的XML和xpath查询放入在线Xpath测试器时,我得到了预期的结果,即“John”
I also can't seem to get any results using substring() and substring-after(). 我似乎也无法使用substring()和substring-after()获得任何结果。 Is something up with PHP's DOMXpath, or am I doing something wrong?
是PHP的DOMX路径,还是我做错了什么?
XPath substring-before()
function returns string
instead of node, and you're not supposed to use DOMXPath::query()
to execute XPath expression that doesn't return node(s)*. XPath
substring-before()
函数返回string
而不是节点,并且您不应该使用DOMXPath::query()
来执行不返回节点*的XPath表达式。 DOMXPath::evaluate()
is the correct function to be used here : DOMXPath::evaluate()
是这里使用的正确函数:
$xml = "<person><name>John-Doe</name></person>";
$doc = new DOMDocument();
$doc->loadXML($xml);
$xpath = new DOMXpath($doc);
$result = $xpath->evaluate("substring-before(/person/name/text(), '-Doe')");
print $result;
output : 输出:
John
*) Quoted from DOMXPath::query > Return Values : *)引自DOMXPath :: query > 返回值 :
Any expression which does not return nodes will return an empty
DOMNodeList
.任何不返回节点的表达式都将返回一个空的
DOMNodeList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.