如何读取外部rss文件?

时间:2010-08-17 08:24:21

标签: php xml symfony1

我应该从另一台服务器的rss文件中显示数据。

当rss文件在我的服务器上时,我可以读取它,但当我尝试在另一台服务器上读取相同的文件时,我得到了这个:

  

警告:   使用simplexml_load_file(rssfile)   [function.simplexml-load-file]:失败   打开流:连接超时   在   的index.php   在第43行

     

警告:simplexml_load_file()   [function.simplexml-load-file]:I / O.   警告:无法加载外部   实体   “rssfile”   在   的index.php   在第43行

这是我的代码:

$actus = simplexml_load_file('rssfile');  
foreach ($actus->channel->item as $actu) 
{  

echo $actu->title;

} 

如何解决?

我认为问题来自Symfony

3 个答案:

答案 0 :(得分:0)

然后你可以用这样的东西来读它...

private static string LoadResource(string rname)
{
    System.IO.Stream s = null;

    try
    {
        s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(rname);
        return new System.IO.StreamReader(s).ReadToEnd();
    }

    finally
    {
        if (s != null)
        {
            s.Dispose();
        }
    }
}

答案 1 :(得分:0)

由于错误/警告消息是“连接超时”,让我们仔细查看超时选项 可以通过default_socket_timeout设置http context option timeoutstream_context_set_default

试试这个

$xmlsrc = 'http://some.host/a/path/foo.rss';
$actus = simplexml_load_file($xmlsrc);
if ( !$actus ) {
  echo "simplexml_load_file() failed.<br />\n";
  echo '$xmlsrc='; var_dump($xmlsrc); echo "<br />\n";
  echo 'default_socket_timeout=', ini_get('default_socket_timeout'), "<br />\n";
  $defaultOptions = stream_context_get_options(stream_context_get_default());
  echo 'default options='; var_dump($defaultOptions); echo "<br />\n";
  die;
}

foreach ($actus->channel->item as $actu) ...

在同一服务器上的两种情况下(有/没有symfony)。 (超时)值是否不同?

答案 2 :(得分:0)

我同意VolkerK,错误来自提供的错误网址。

另外,当您使用symfony时,我建议您使用sfFeed2Plugin,它将比simplexml加载器(验证,输出方法,甚至,如果需要,服务)做更多的事情。

以下是一个快速使用示例:

// define your source url
$source_url = 'http://feeds.feedburner.com/TechCrunch';

// fetch url
if($feed = sfFeedPeer::createFromWeb($source_url))
{
  // get items
  $items = $feed->getItems();

  foreach($items as $item)
  {
    // do whatever you want with each item
    echo $item->getTitle()."\n";
  }
}