2013-09-28 50 views
-1

我是新來的XML,我得到了RSS從website.com/rss.php料中的XML如何將XML(rss.php)轉換爲html?

<rss version="0.91"> 
<channel> 
<title>News</title> 
<description>Powered by website.com</description> 
<link>http://www.website.com/</link> 
<language>en-gb</language> 
<item> 
<title> 
Product Title 1 
</title> 
<link> 
http://www.website.com/link-to-product-page.html 
</link> 
<pubDate>Fri, 27 Sep 2013 17:40:29 +0100</pubDate> 
<description> 
<![CDATA[ 
<img src="http://www.website.com/images/product_image_1.jpg"/> Product Description 1 ]]> 
</description> 
</item> 
<item> 
<title> 
(...) 
</description> 
</item> 
</channel> 
</rss> 

我想將其轉換爲HTML。有什麼建議? :)

+0

[問題作爲代碼之王必須證明對所解決問題的最小理解。包括嘗試的解決方案,爲什麼他們不工作,以及預期的結果。](http://stackoverflow.com/help/on-topic)。 – IMSoP

回答

1

您可以使用simplexmlelement
試試這個代碼:

<?php 
$news=new SimpleXMLElement(' 
<rss version="0.91"> 
    <channel> 
     <title>News</title> 
     <description> 
      Powered by website.com 
     </description> 
     <link> 
     http://www.website.com/</link> 
     <language> 
      en-gb 
     </language> 
     <item> 
      <title> Product Title 1 </title> 
      <link> 
      http://www.website.com/link-to-product-page.html 
      </link> 
      <pubDate> 
       Fri, 27 Sep 2013 17:40:29 +0100 
      </pubDate> 
      <description> 
       <![CDATA[ 
       <img src="http://www.website.com/images/product_image_1.jpg"/> Product Description 1 ]]> 
      </description> 
     </item> 
     <item> 
      <title> Product Title 1 </title> 
      <link> 
      http://www.website.com/link-to-product-page.html 
      </link> 
      <pubDate> 
       Fri, 27 Sep 2013 17:40:29 +0100 
      </pubDate> 
      <description> 
       <![CDATA[ 
       <img src="http://www.website.com/images/product_image_1.jpg"/> Product Description 1 ]]> 
      </description> 
     </item> 
    </channel> 
</rss>'); 
foreach ($news->channel->item as $value) { 
    echo '<div>'; 
    echo '<h2>'.$value->title.'</h2>'; 
    echo '<div>'.$value->link.'</div>'; 
    echo '<div>'.$value->pubDate.'</div>'; 
    echo '</div>'; 
} 
?> 
+2

因爲這是XML,而不是HTML,並且非常簡單,所以您可以使用內置的[SimpleXML](http://uk3.php.net/simplexml)擴展。 – IMSoP

+0

@IMSoP TNX通知。 ;) – ops

+1

否。使用PHP內置的SimpleXML類。這是一個可怕的答案。 –

2

PHP的SimpleXML

http://php.net/manual/en/book.simplexml.php

例:

<?php 
    $xml = simplexml_load_file('http://www.website.com/rss.php'); 
    $news = new SimpleXMLElement($xml); 
?> 

<?php foreach ($news->channel->item as $story):?> 
    <h1><?=$story->title?></h1> 
    <div><?=$story->description?></div> 
<?php endforeach ?> 
+2

就個人而言,我不會使用這個的<?='和'endforeach'部分,但它恰如其分地證明了SimpleXML的名稱:) – IMSoP