【问题标题】:Using SimplePie and Simple HTML DOM together一起使用 SimplePie 和 Simple HTML DOM
【发布时间】:2016-01-24 00:45:55
【问题描述】:

我正在尝试使用 SimplePie 通过 RSS 提要提取链接列表,然后使用 Simple HTML DOM 抓取这些提要以提取图像。我能够让 SimplePie 工作以提取链接并将它们存储在一个数组中。我还可以使用 Simple HTML DOM 解析器来获取我正在寻找的图像链接。问题是当我尝试同时使用 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 数组,代码将全部运行而没有错误,但不会给我想要的结果 - 当然。非常感谢任何帮助!

【问题讨论】:

    标签: php simple-html-dom simplepie


    【解决方案1】:

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

    奇怪的是,传递给函数模式而不是对象模式,对我来说效果很好:

    $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(),你的代码应该可以工作了。否则,您可以使用我上面的代码或将 html 数据预加载到变量中,然后调用 simple_html_dom->load() 而不是 simple_html_dom->load_file()

    【讨论】:

    • 太棒了,fusion3k。我的服务器没有达到 PHP 7,所以我选择了你的第一个解决方案,它运行良好。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2016-04-09
    • 2013-09-05
    相关资源
    最近更新 更多