doutenglou6588 2011-09-29 13:35 采纳率: 0%
浏览 125

PHP致命错误:无法将字符串解析为XML

I'm trying to include an RSS feed on my website. The following code works locally but causes a fatal error on the live site:

<?php
// Initialise the cURL resource handle:
$ch = curl_init("http://www.blogs.stopjunkmail.org.uk/diary/index.php?/feeds/index.rss2");
// Set connection options:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
// Execute connection, wait for response, and close:
$data = curl_exec($ch);
curl_close($ch);
// Parse the data:
$doc = new SimpleXmlElement($data, LIBXML_NOCDATA);
// Define the function to parse RSS:
function parseRSS($doc) {
    echo '<ul>' . "
";
    for($i=0; $i<5; $i++) {
        $url    = $doc->channel->item[$i]->link;
        $title  = $doc->channel->item[$i]->title;
        $date   = $doc->channel->item[$i]->pubDate;
        echo '<li>' . "
";
        echo '<a href="'.$url.'">'.$title.'</a>' . "
";
        echo '</li>' . "
";
    }
    echo '</ul>' . "
";
}
?>
<!doctype html>
<html lang="en-GB">
<head>
 <meta charset="UTF-8" />
 <title>Test feed</title>
</head>
<body>

 <h2>Recent blog entries</h2>
<?php parseRSS($doc); ?>

</body>
</html>

This causes the following errors:

[Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx] PHP Fatal error:  Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/sites/stopjunkmail.org.uk/public_html/news/_test.php:11
[Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx] Stack trace:
[Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx] #0 /home/sites/stopjunkmail.org.uk/public_html/news/_test.php(11): SimpleXMLElement->__construct('', 16384)
[Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx] #1 {main}
[Thu Sep 29 12:06:28 2011] [error] [client xx.xx.xx.xxx]   thrown in /home/sites/stopjunkmail.org.uk/public_html/news/_test.php on line 11

After lots of trial and error and looking up similar questions I've found it's the feed that's causing the problem. If I change the feed to a very basic sample feel (for instance http://feedparser.org/docs/examples/rss20.xml) it all works fine. The feed I'm trying to parse is valid (though has some warnings).

Question is... what do I need to do get the script to accept the feed?

  • 写回答

2条回答 默认 最新

  • doushi2902 2011-09-29 13:49
    关注

    Maybe another option to force the MIME type?

    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: text/xml'));
    

    EDIT: Could also be a problem with cURL on your webserver compared to your local environment. If the PHP versions are different then that could be an issue.

    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程