如何在XPATH
中register
PHP
功能?因为XPATH
不允许我使用ends-with()
这是一个成员给出的解决方案,但它不起作用。
他使用的代码是:
$xpath = new DOMXPath($document);
$xpath->registerNamespace("php", "http://php.net/xpath");
$xpath->registerPHPFunctions("ends_with");
$nodes = $x->query("//tr[/td/a/img[php:function('ends-with',@id,'_imgProductImage')]"
function ends_with($node, $value){
return substr($node[0]->nodeValue,-strlen($value))==$value;
}
我正在使用 PHP 5.3.9。
在您的问题中,它看起来像一个错字,没有名为 ends-with
的函数,因此我希望它不起作用:
//tr[/td/a/img[php:function('ends-with',@id,'_imgProductImage')]
^^^^^^^^^
而是使用正确的语法,例如正确的函数名称:
//tr[/td/a/img[php:function('ends_with',@id,'_imgProductImage')]
^^^^^^^^^
或者例如,如以下示例所示:
书.xml:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>PHP Basics</title>
<author>Jim Smith</author>
<author>Jane Smith</author>
</book>
<book>
<title>PHP Secrets</title>
<author>Jenny Smythe</author>
</book>
<book>
<title>XML basics</title>
<author>Joe Black</author>
</book>
</books>
.PHP:
<?php
$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");
// Register PHP functions (no restrictions)
$xpath->registerPHPFunctions();
// Call substr function on the book title
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');
echo "Found {$nodes->length} books starting with 'PHP':'n";
foreach ($nodes as $node) {
$title = $node->getElementsByTagName("title")->item(0)->nodeValue;
$author = $node->getElementsByTagName("author")->item(0)->nodeValue;
echo "$title by $author'n";
}
如您所见,此示例注册所有 PHP 函数,包括现有的 substr()
函数。
有关详细信息,请参阅DOMXPath::registerPHPFunctions
,这也是代码示例的来源。
我希望这是有帮助的,如果您仍然对此有疑问,请告诉我。
另请参阅:
- 如何在 php 中使用 preg 添加 html 属性 (2010 年 8 月)
- 在 PHP XPath->evaluate 中使用正则表达式(2011 年 11 月)
- 获取在 Xpath (PHP) (2012 年 7 月)中以大写开头的标记;具体来说就是这个答案。
- 从一堆xml文件中特定正则表达式模式的搜索结果中获取xpath(2013年3月);具体来说就是这个答案。