📅  最后修改于: 2023-12-03 14:45:14.551000             🧑  作者: Mango
在 PHP 中,DOMXPath evaluate() 函数是一个用于计算 XPath 表达式的函数。它可以从一个 DOM 文档中选择节点,返回一个节点对象、节点列表、字符串、数字、布尔值等类型的值。
DOMNodeList|DOMElement|DOMAttr|boolean|string|float|null evaluate(string $expression[, DOMNode $contextnode[, boolean $register_ns = TRUE]]);
参数:
$expression
:要计算的 XPath 表达式$contextnode
:可选参数,要在其上下文中计算 XPath 表达式的起始节点,默认为整个文档。可以是 DOMElement、DOMDocument、DOMXPath 对象。$register_ns
:可选参数,是否注册命名空间,默认为 TRUE。返回值类型:
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<title>PHP & MySQL Tutorial</title>
<title>jQuery Tutorial</title>
<title>XPath Tutorial</title>
</root>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$titles = $xpath->evaluate('//title');
foreach ($titles as $title) {
echo $title->nodeValue . "\n";
}
?>
输出:
PHP & MySQL Tutorial
jQuery Tutorial
XPath Tutorial
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<title>PHP & MySQL Tutorial</title>
<title>jQuery Tutorial</title>
<title>XPath Tutorial</title>
</root>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$titles = $xpath->evaluate('/root/title');
foreach ($titles as $title) {
echo $title->nodeValue . "\n";
}
?>
输出:
PHP & MySQL Tutorial
jQuery Tutorial
XPath Tutorial
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root>
<title>PHP & MySQL Tutorial</title>
<title>jQuery Tutorial</title>
<title>XPath Tutorial</title>
</root>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$result = $xpath->evaluate('/root/title[1]/text() = "PHP & MySQL Tutorial"');
var_dump($result); // bool(true)
?>
<?php
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:foo="http://www.example.com/foo">
<foo:title>PHP & MySQL Tutorial</foo:title>
<foo:title>jQuery Tutorial</foo:title>
<foo:title>XPath Tutorial</foo:title>
</root>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('foo', 'http://www.example.com/foo');
$titles = $xpath->evaluate('/root/foo:title');
foreach ($titles as $title) {
echo $title->nodeValue . "\n";
}
?>
输出:
PHP & MySQL Tutorial
jQuery Tutorial
XPath Tutorial
以上是关于 PHP | DOMXPath evaluate()函数 的介绍,如果您想了解更多相关内容,可以访问 PHP Handbook。