一起使用SimplePie和简单的HTML DOM
我想使用SimplePie通过RSS源拉动链接列表,然后使用简单的HTML DOM拖动这些源来拉出图像。我能够让SimplePie工作来拉链接并将它们存储在一个数组中。我也可以使用Simple HTML DOM解析器来获取我正在寻找的图像链接。问题是,当我尝试同时使用SimplePie和Simple HTML DOM时,出现500错误。下面的代码:一起使用SimplePie和简单的HTML DOM
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);
}
我注释掉网址阵列,但它是与由循环了SimplePie创建阵列(I创建它手动从结果)。第一次通过循环时find命令失败。如果我注释掉$ rss-> init()行并使用静态url数组,那么所有代码都运行时没有错误,但不会给我我想要的结果 - 当然。任何帮助是极大的赞赏!
simple_html_dom
和SimplePie
之间存在奇怪的不兼容性。加载html,simple_html_dom->root
未加载,导致任何其他操作的错误。
奇怪的是,路过的功能模式,而不是对象的模式,这对我来说工作得很好:的
$html = file_get_html($url);
代替:
$html = new simple_html_dom();
$html->load_file($url);
反正simple_html_dom
是众所周知的导致的问题,首先关于内存使用情况。
编辑:
OK,我发现的bug。 它驻留在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()
,你的代码应该可以工作。否则,您可以使用我上面的代码或将HTML数据预加载到变量,然后调用simple_html_dom->load()
而不是simple_html_dom->load_file()
太棒了,fusion3k。我的服务器没有达到PHP 7,所以我用你的第一个解决方案,它运行得很好。谢谢! –