简单的xml解析

时间:2011-03-21 15:48:42

标签: php rss simplexml

首先我是一个PHP菜鸟, 以为我有简单的xml,但显然不是:)

我只是试图解析一个新闻源并将其回显,但我什么都没得到,而且没有任何错误消息让它变得更难。我可能犯了一个愚蠢的错误......

继承了我写的代码:

<?php

$rss = simplexml_load_file('http://feeds.bbci.co.uk/news/world/rss.xml');

foreach($rss->channel->item as $item) {

    $title = $item['title'];

    echo $title;
    echo '<br /><hr />';
}

?>

下面是xml布局的一个例子:

 

<rss xmlns:media="http://search.yahoo.com/mrss/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">  
  <channel> 
    <title>BBC News - World</title>  
    <link>http://www.bbc.co.uk/go/rss/int/news/-/news/world/</link>  
    <description>The latest stories from the World section of the BBC News web site.</description>  
    <language>en-gb</language>  
    <lastBuildDate>Mon, 21 Mar 2011 14:31:31 GMT</lastBuildDate>  
    <copyright>Copyright: (C) British Broadcasting Corporation, see http://news.bbc.co.uk/2/hi/help/rss/4498287.stm for terms and conditions of reuse.</copyright>  
    <ttl>15</ttl>  
    <atom:link href="http://feeds.bbci.co.uk/news/world/rss.xml" rel="self" type="application/rss+xml"/>  
    <item> 
      <title>Gaddafi 'not targeted' by strikes</title>  
      <description>Coalition forces carrying out operations against Libyan government forces say Colonel Gaddafi himself is not a target, despite a strike on his compound.</description>  
      <link>http://www.bbc.co.uk/go/rss/int/news/-/news/world-africa-12802939</link>  
      <guid isPermaLink="false">http://www.bbc.co.uk/news/world-africa-12802939</guid>  
      <pubDate>Mon, 21 Mar 2011 14:39:21 GMT</pubDate>  
      <media:thumbnail width="66" height="49" url="http://news.bbcimg.co.uk/media/images/51766000/jpg/_51766446_011582753-1.jpg"/>  
      <media:thumbnail width="144" height="81" url="http://news.bbcimg.co.uk/media/images/51766000/jpg/_51766444_011582753-1.jpg"/> 
    </item>
  </channel> 
</rss> 

任何人都可以看到我的代码有任何明显的错误吗?香港专业教育学院之前使用它并且工作正常:(

谢谢你的时间,

alsweet

1 个答案:

答案 0 :(得分:3)

试试这个:

foreach($rss->channel->item as $item) {

    $title = (string)$item->title[0];

    echo $title;

}