简体   繁体   中英

Can't get PHP DOMXpath substring functions to work

Using the following PHP code sample:

$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

But when I put the same XML and xpath query into online Xpath testers, I get the expected result, which is "John"

I also can't seem to get any results using substring() and substring-after(). Is something up with PHP's DOMXpath, or am I doing something wrong?

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)*. DOMXPath::evaluate() is the correct function to be used here :

$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;

eval.in demo

output :

John

*) Quoted from DOMXPath::query > Return Values :

Any expression which does not return nodes will return an empty DOMNodeList .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM