How to register PHP function in XPath?

吃可爱长大的小学妹 提交于 2020-01-05 08:36:11

问题


How can I register PHP function in XPATH? Because XPATH does not allows me to use ends-with()

Here is one solutions given by one member but it does not works with.

The code he has used is:

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

I am using PHP 5.3.9.


回答1:


In your question it looks like a typo, there is no function named ends-with therefore I would expect it not to work:

//tr[/td/a/img[php:function('ends-with',@id,'_imgProductImage')]
                             ^^^^^^^^^

Instead use the right syntax, e.g. the correct function name:

//tr[/td/a/img[php:function('ends_with',@id,'_imgProductImage')]
                             ^^^^^^^^^

Or for example like with the following example:

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";
}

As you can see, this example registers all PHP functions including the existing substr() function.

See DOMXPath::registerPHPFunctions for more information, that is also where the code example has been taken from.

I hope this is helpful, let me know if you still have a question about this.

See as well:

  • 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); in specific this answer.
  • Get xpath from search result of a specific regex pattern in a bunch of xml files (Mar 2013); in specific this answer.


来源:https://stackoverflow.com/questions/19563167/how-to-register-php-function-in-xpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!