【问题标题】:Fatal error: Uncaught Error: Call to a member function find() on string while parsing data致命错误:未捕获的错误:在解析数据时调用字符串上的成员函数 find()
【发布时间】:2018-10-08 19:32:41
【问题描述】:

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

<?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} 在 C:\Server 中抛出\XAMPP\htdocs\pan\index.php 在第 21 行

第 21 行是:

foreach($html->find("p") as $element)

【问题讨论】:

  • 如果您发布完整的代码sn-p会更容易提供帮助。尝试打印$html 以确保正在读取文件?看起来你得到的是一个字符串而不是 HTML。
  • 这是所有代码:)
  • 编辑:几行没有显示,mb,现在显示所有内容
  • 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-&gt;getElementsByTagName("p") as $element){ echo $element-&gt;textContent. '&lt;br&gt;'; }

标签: php curl dom html-parsing simple-html-dom


【解决方案1】:

我认为file_get_contents_curl 是在调用它上面返回$data 的函数。

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

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

或者你可以使用:

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

完全避免卷曲。

【讨论】:

  • 这个有助于解决错误,但不幸的是,我只能从这个页面获取标题,有什么解决方案吗?
  • 如果您在浏览器中访问该页面并查看页面源代码,您会看到所有 HTML 都是通过 javascript 加载的,这就是为什么您只能看到标题。不幸的是,我不相信 PHP 有任何方法可以呈现它。您可以尝试谷歌搜索“在 PHP 中呈现页面”?
  • 您可能会发现这篇文章很有用:stackoverflow.com/questions/50085261/…
  • 再次感谢,我研究了一下,发现 phantom js 非常有用。感谢您为我指明正确的方向:)
猜你喜欢
  • 2016-10-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 2023-03-27
  • 2018-09-10
  • 2022-01-20
  • 1970-01-01
相关资源
最近更新 更多