dongzhun8449 2013-10-24 10:17
浏览 30
已采纳

如何在XPath中注册PHP函数?

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条回答 默认 最新

  • duanhua9398 2013-10-24 12:34
    关注

    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':
    ";
    foreach ($nodes as $node) {
        $title  = $node->getElementsByTagName("title")->item(0)->nodeValue;
        $author = $node->getElementsByTagName("author")->item(0)->nodeValue;
        echo "$title by $author
    ";
    }
    

    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:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题