编程语言
首页 > 编程语言> > PHP – DOMXpath – 获取结果

PHP – DOMXpath – 获取结果

作者:互联网

当我想用XPath打印evaluate表达式的结果时,我有错误.

$url = $xpath-> evaluate(‘// a / @ href’,$event);
echo $url;

我有这个错误:可捕获的致命错误:类DOMNodeList的对象无法转换为字符串

我的代码:

<?php
    // Get the HTML Source Code
    $url='http://www.parisbouge.com/events/2012/05/01/';
    $source = file_get_contents($url);

    // DOM document Creation
    $doc = new DOMDocument;
    $doc->loadHTML($source);

    // DOM XPath Creation
    $xpath = new DOMXPath($doc);

    // Get all events
    $events = $xpath->query('//li[@class="nom"]');

    // Count number of events
    printf('There is %d events<br />', $events->length);

    // List all events
    for($i = 0; $i < ($events->length); $i++) {
        $event = $events->item($i);
        $url = $xpath->evaluate('//a/@href', $event);
        $nom = $xpath->evaluate('//a/text()', $event);
        $lieu = $xpath->evaluate('../li[@class="lieu"]/a/text()', $event);
        echo "Result : $url $nom $lieu <br/>";
    }
?>

解决方法:

尝试此操作以获取有关节点的信息.

 // List all events
for($i = 0; $i < ($events->length); $i++) {
    $event = $events->item($i);
    $url = $xpath->evaluate('.//a/@href', $event);
    $nom = $xpath->evaluate('.//a/text()', $event);
    $lieu = $xpath->evaluate('../li[@class="lieu"]/a/text()', $event);

    $result = '';
    if ($url->length > 0) {
        $result .= $url->item(0)->value;
    }

    if ($nom->length > 0) {
        $result .= $nom->item(0)->wholeText;
    }

    if ($lieu->length > 0) {
        $result .= $lieu->item(0)->wholeText;
    }

    echo $result . "<br />";
    //echo "Result : " . $url->item(0)->value . ' | ' . $nom->item(0)->wholeText  . ' | ' . $lieu->item(0)->wholeText . "<br/>";
}

不要忘记添加检查节点是否存在等.要检查是否有任何节点,您可以检查nodeList lenght或抑制“Gordon”建议的错误.

标签:php,xpath,evaluate,domdocument,domxpath
来源: https://codeday.me/bug/20190723/1513067.html