【问题标题】:Call to a member function find() on null in PHP Simple HTML DOM在 PHP Simple HTML DOM 中调用 null 上的成员函数 find()
【发布时间】:2022-01-03 19:15:51
【问题描述】:

我打算使用PHP Simple HTML DOM 提取this link中的链接

我写的代码如下:

$url = "https://www.technolife.ir/product-3303";        
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_REFERER, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$str = curl_exec($curl);
curl_close($curl);
$html_base = new simple_html_dom();

foreach($html_base->find('a') as $element) {
    echo "<pre>";
    print_r( $element->href );
    echo "</pre>";
}


但不幸的是,我在运行时遇到了这个错误:

Call to a member function find() on null

【问题讨论】:

  • 这段代码不会发生这种情况。 new 永远无法返回 null
  • 不应该是simple_html_dom($str)吗?
  • @Barmar 我尝试了你的建议,但它给了我这个错误:is_file() expects parameter 1 to be a valid path, string given
  • @hanshenrik 你也可以自己试试这个链接的代码,看看会出现什么错误
  • @hanshenrik simple_html_dom 不是用户编写的类,是第三方库simplehtmldom.sourceforge.io

标签: php curl simple-html-dom


【解决方案1】:

https://www.technolife.ir/product-3303 即使在客户端不请求压缩时也提供 gzip 压缩的内容,因此您只会得到一堆二进制 gzip 压缩的数据,这些数据看起来对 simplehtmldom 来说完全是垃圾并导致其崩溃。

幸运的是 libcurl 内置了对 gzip 解压的支持,可以通过curl_setopt($curl, CURLOPT_ENCODING, ''); 启用

也就是说,您应该使用 DOMDocument 而不是 simple_html_dom,

$html_base = new DOMDocument();
@$html_base->loadHTML($str);
foreach($html_base->getElementsByTagName('a') as $element) {
    echo "<pre>";
    print_r( $element->getAttribute("href") );
    echo "</pre>";
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-06
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多