gpt4 book ai didi

PHP - DOMXpath - 获取结果

转载 作者:可可西里 更新时间:2023-11-01 00:10:16 24 4
gpt4 key购买 nike

当我想用 XPath 打印计算表达式的结果时出现错误。

$url = $xpath->evaluate('//a/@href', $event);回显 $url ;

我有这个错误:可捕获的 fatal error :类 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 长度或按照“Gordon”的建议抑制错误。

关于PHP - DOMXpath - 获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10396245/

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