一起使用 SimplePie 和 Simple HTML DOM

Using SimplePie and Simple HTML DOM together

我正在尝试使用 SimplePie 通过 RSS 提要提取 link 的列表,然后使用 Simple HTML DOM 抓取这些提要以提取图像。我能够让 SimplePie 工作以提取 links 并将它们存储在一个数组中。我还可以使用 Simple HTML DOM 解析器来获取我正在寻找的图像 link。问题是,当我尝试同时使用 SimplePie 和 Simple HTML DOM 时,出现 500 错误。这是代码:

set_time_limit(0);
error_reporting(0);

$rss = new SimplePie();
$rss->set_feed_url('http://contently.com/strategist/feed/');
$rss->init();

foreach($rss->get_items() as $item)
  $urls[] = $item->get_permalink();
unset($rss);

/*
$urls = array(
'https://contently.com/strategist/2016/01/22/whats-in-a-spotify-name-and-5-other-stories-you-should-read/',
'https://contently.com/strategist/2016/01/22/how-to-make-content-marketing-work-inside-a-financial-services-company/',
'https://contently.com/strategist/2016/01/22/glenn-greenwald-talks-buzzfeed-freelancing-the-future-journalism/',
...
'https://contently.com/strategist/2016/01/19/update-a-simpler-unified-workflow/');
*/ 

foreach($urls as $url) {
  $html = new simple_html_dom();
  $html->load_file($url);
  $images = $html->find('img[class=wp-post-image]',0);
  echo $images;
  $html->clear();
  unset($html);
}

我注释掉了 urls 数组,但它与 SimplePie 循环创建的数组相同(我根据结果手动创建它)。它在循环中第一次执行 find 命令失败。如果我注释掉 $rss->init() 行并使用静态 url 数组,代码将全部运行且没有错误,但不会给我想要的结果 - 当然。非常感谢任何帮助!

simple_html_domSimplePie 之间存在奇怪的不兼容性。正在加载html,未加载simple_html_dom->root,导致其他操作出错。

奇怪的是,传递给 function-mode 而不是 object-mode,对我来说它工作正常:

$html = file_get_html( $url );

而不是:

$html = new simple_html_dom();
$html->load_file($url);

无论如何,simple_html_dom 是众所周知的问题,尤其是内存使用问题。

已编辑:

好的,我找到了错误。 它驻留在 simple_html_dom->load_file() 上,调用标准函数 file_get_contents(),然后通过 error_get_last() 检查结果,并且 - 如果发现错误 - 取消设置自己的数据。但是,如果之前发生错误(在我的测试中 SimplePie 输出警告 ./cache is not writeable),这个先前的错误被 simple_html_dom 解释为 file_get_contents() 失败。

如果您安装了 PHP 7,您可以在 unset($rss) 之后调用 error_clear_last(),您的代码应该可以工作。否则,您可以使用我上面的代码或 pre-load html 数据到变量,然后调用 simple_html_dom->load() 而不是 simple_html_dom->load_file()