如何使用PHP获取格式的xml数据

时间:2013-11-01 14:55:35

标签: php xml rss simplexml

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="itemcontent.css"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="feedburner/ext/1.0" version="2.0">
<channel>
<title>NewsP</title>
<link>http://newscom/</link>

<description>News - Page A RSS</description>
<pubDate>Thu, 31 Oct 2013 16:22:54 GMT</pubDate>
<lastBuildDate>Thu, 31 Oct 2013 16:22:54 GMT</lastBuildDate>
<language>zh-TW</language>
<category>Newspaper</category>
<copyright>Copyright (C) 1998 News</copyright>



<image><title>news - Page A</title><url>logo1.jpg</url><link>dailydotcom/</link></image>
<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="pga" /><feedburner:info uri="pga" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://snufkinto.superfeedr.com/" /><geo:lat>22.1923</geo:lat><geo:long>113.5438</geo:long><creativeCommons:license>http://creativecommons.org/licenses/by-nc-nd/2.0/</creativeCommons:license><meta xmlns="http://pipes.yahoo.com" name="pipes" content="noprocess" /><item>

<title><![CDATA[A01.Ad - ]]></title>

<link>e_2.htm</link>
<description>&lt;img src=39451383243502891.jpg border=0&gt;&lt;div class="feedflare"&gt;
&lt;a href="pga?a=fry0sdpGTNM:pV-KRaLgwSI:yIl2AUoC8zA"&gt;&lt;img src="yIl2AUoC8zA" border="0"&gt;&lt;/img&gt;&lt;/a&gt; &lt;a href="fry0sdpGTNM:pV-KRaLgwSI:qj6IDK7rITs"&gt;&lt;img src="pga?d=qj6IDK7rITs" border="0"&gt;&lt;/img&gt;&lt;/a&gt;
&lt;/div&gt;&lt;img src="fry0sdpGTNM" height="1" width="1"/&gt;</description>
<guid isPermaLink="false">node_2.htm</guid>
<pubDate>Thu, 31 Oct 2013 16:22:54 GMT</pubDate>
<category>Ad</category>
<author>com (Remus To)</author>
<feedburner:origLink>http://e_2.htm</feedburner:origLink></item>

<item>
<title><![CDATA[A02.Ad - ]]></title>
...
...
...
</channel>
</rss>

如何使用<title>等提取新闻<description><category>foreach

这是我的代码:

<?php    

$movies = new SimpleXMLElement(file_get_contents("xml"));

foreach ($movies->channel->item->title as $title) {    
   echo $title, description, category,xxx,xxx,xxx, PHP_EOL;
   ####only one result echo!    
}    

?>

我的代码只能回显一个结果,我的意思是我有很多新的,如何得到它们?感谢

1 个答案:

答案 0 :(得分:1)

您正在迭代第一个标题 ,因为您只是在第一个项目的第一个标题上进行迭代。

相反,您希望迭代所有项目,然后获取每个项目的标题:

foreach ($movies->channel->item as $item)
{
    echo $item->title, PHP_EOL;
}

输出:

A01.Ad - 
A02.Ad - 

这就是全部,这通常在PHP Simplexml Basic Usage Examples中列出,我建议您在那里阅读以防万一卡住。