0

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

它在我的测试环境中完美运行,但是当我将它放在我的网站上时,每次必须写入缓存文件时都会出错:

警告:DOMDocument::load(): I/O warning : failed to load external entity ".../rssRadio.xml.cache" in .../index.php on line 45

这是页面的代码。第 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 调用……对吧?有任何想法吗?

干杯

4

1 回答 1

1

问题可能在于服务器延迟更新索引树。usleep(100);您可以添加一个after来解决它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' );
}

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

于 2016-04-05T12:07:16.547 回答