PHP:DOMDocument :: load():I / O警告:无法加载外部实体(外部RSS提要和缓存文件)

时间:2016-04-05 11:03:29

标签: php xml caching domdocument file-put-contents

我需要在我的页面上显示来自外部RSS提要的最新条目。 我制作了一个使用缓存文件的简单rss阅读器。

它完全适用于我的测试环境但是当我把它放在我的网站上时,每次写入缓存文件时都会出错:

警告:DOMDocument :: load():I / O警告:无法加载外部实体" ... / rssRadio.xml.cache"在第45行的... / index.php

这是页面的代码。第45行是最后一行:

      $cacheName = 'cache/rss.xml.cache';
        $ageInSeconds = (3600*2); // two hour
        if(!file_exists($cacheName) || filemtime($cacheName) < time() - $ageInSeconds ) {
          $contents = file_get_contents($RSSURL);
          file_put_contents($cacheName, $contents);
        }
        $rss = new DOMDocument();
        if (!$rss->load($cacheName)) {
            throw new Exception('Impossibile caricare i podcast');
         }
        $feed = array();
        foreach ($rss->getElementsByTagName('item') as $node) {
     

...

如果我重新加载页面,则错误消失并显示内容,因此缓存文件正常工作。

在file_put_contents调用结束之前,它看起来像是在尝试读取缓存文件的脚本。但这是不可能的,因为这是一个阻塞的I / O调用......对吗? 有什么想法吗?

干杯

1 个答案:

答案 0 :(得分:1)

问题可能在于更新索引树的服务器延迟。您可以在usleep(100);之后添加file_put_contents来解决此问题。

但是,在我看来,最好的解决方案是这样的:

if(!file_exists($cacheName) || filemtime($cacheName) < time() - $ageInSeconds ) 
{
    $contents = file_get_contents( $RSSURL );
    file_put_contents( $cacheName, $contents );
}
else
{
    $contents = file_get_contents( $cacheName );
}
$rss = new DOMDocument();
if( !$rss->loadXML( $contents ) ) 
{
    throw new Exception( 'Impossibile caricare i podcast' );
}

通过这种方式,您加载字符串而不是文件,您的脚本将正常工作。