gpt4 book ai didi

php - 如何在XPath中注册PHP函数?

转载 作者:行者123 更新时间:2023-12-03 17:04:26 32 4
gpt4 key购买 nike

register PHP如何在XPATH中起作用?因为XPATH不允许我使用ends-with()

这是一个成员提供的一个solutions,但不能使用。

他使用的代码是:

$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')]
^^^^^^^^^


或例如以下示例:

book.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,这也是从中获取代码示例的地方。

希望对您有所帮助,如果您还有其他疑问,请告诉我。

另请参阅:


How to use preg in php to add html properties (Aug 2010)
Using Regex in PHP XPath->evaluate (Nov 2011)
Get tags that start with uppercase in Xpath (PHP) (Jul 2012);在特定的 this answer中。
Get xpath from search result of a specific regex pattern in a bunch of xml files (Mar 2013);在特定的 this answer中。

关于php - 如何在XPath中注册PHP函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19563167/

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