致命错误:未捕获错误:在解析数据时调用字符串上的成员函数 find()

Fatal error: Uncaught Error: Call to a member function find() on string while parsing data

提问人:Hotshot 提问时间:4/28/2018 最后编辑:Hotshot 更新时间:4/28/2018 访问量:3557

问:

因此,我尝试从这个网页 https://promo.pan.com.hr 使用 curl 和简单的 HTML dom 获取一些信息。但不幸的是,我不断收到错误,我无法弄清楚出了什么问题......

<?php
include_once("simple_html_dom.php");
function file_get_contents_curl($url)
{
$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

$data = curl_exec($ch);
curl_close($ch);

return $data;
}

$html = file_get_contents_curl("https://promo.pan.com.hr");


foreach($html->find("p") as $element)
echo $element->innertext . '<br>';
?>

有人知道我为什么会收到这个错误吗?

致命错误:未捕获的错误:调用 C:\Server\XAMPP\htdocs\pan\index.php:21 中字符串的成员函数 find() 堆栈跟踪:#0 {main} 在第 21 行的 C:\Server\XAMPP\htdocs\pan\index.php 中抛出

第 21 行是:

foreach($html->find("p") as $element)
php curl 解析 simple-html-dom

评论

0赞 theUtherSide 4/28/2018
如果您发布完整的代码片段,则会更容易提供帮助。尝试打印以确保文件正在被读取?看起来你得到的是一个字符串而不是 HTML。$html
0赞 Hotshot 4/28/2018
这就是所有代码:)
0赞 Hotshot 4/28/2018
编辑:有几行没有显示,mb,现在正在显示所有内容
0赞 hanshenrik 4/29/2018
file_get_contents_curl返回一个字符串,那么你就试图把它作为一个对象来使用,这正是PHP所抱怨的。老实说,不要使用simple_html_dom,它已经过时了,已经很久了,请改用 DOMDocument。$html = file_get_contents_curl("https://promo.pan.com.hr");$domd=@DOMDocument::loadHTML($html); foreach($domd->getElementsByTagName("p") as $element){ echo $element->textContent. '<br>'; }

答:

1赞 Nick 4/28/2018 #1

我推测是在调用它上方返回的函数。file_get_contents_curl$data

您的问题是返回一个字符串,该字符串是网页的内容。我假设您正在使用哪种情况下,您需要先将该字符串转换为对象:[curl_exec][1]simple_html_domsimple_html_dom

$html = str_get_html(file_get_contents_curl("https://promo.pan.com.hr"));

或者你可以只使用:

$html = file_get_html("https://promo.pan.com.hr");

并完全避免卷曲。

评论

0赞 Hotshot 4/28/2018
这个有助于解决错误,但不幸的是,我只能从此页面获取标题,该问题的任何解决方案?
0赞 Nick 4/28/2018
如果你在浏览器中访问该页面并查看页面源代码,你会看到所有的HTML都是通过javascript加载的,这就是为什么你只能看到标题。不幸的是,我不相信PHP中有任何方法可以呈现它。您可以尝试在谷歌上搜索“在 PHP 中渲染页面”?
0赞 Nick 4/29/2018
您可能会发现这篇文章很有用:stackoverflow.com/questions/50085261/...
0赞 Hotshot 4/30/2018
再次感谢,我正在研究一些,发现 phantom js 非常有用。谢谢你为我指明了正确的方向:)