2010-11-16 85 views
0

我對DOM文檔是完全陌生的,基本上我正在嘗試做的是加載一個RSS提要並僅選擇一個節點,然後將其保存到XML文件中。訪問單個XML DOM文檔節點

這裏是我從網絡供稿加載XML:

<?xml version="1.0" encoding="UTF-8"?> 
<rss version="2.0"> 
    <channel> 
     <title>Markets</title> 
     <description/> 
     <link>http://www.website.com</link> 
     <language>en-us</language> 
     <copyright>XML Output Copyright</copyright> 
     <ttl>15</ttl> 
     <pubDate>Tue, 16 Nov 2010 09:38:00 +0000</pubDate> 
     <webMaster>[email protected]</webMaster> 
     <image> 
      <title>title</title> 
      <url>http://www.website.com/images/xmllogo.gif</url> 
      <link>http://www.website.com</link> 
      <width>144</width> 
      <height>16</height> 
     </image> 


      <item> 
       <title>title</title> 
       <description>the description goes here 
       </description> 
       <enclosure url="http://www.website.com/images/image.png" type="image/png"/> 

      </item> 

    </channel> 
</rss> 

這是我在獲得<description>節點並保存跛腳企圖feed.xml:

<?php 

    $feed = new DOMDocument(); 
    $feed->load('http://www.website.com/directory/directory/cz.c'); 
    $nodeValue = $feed->getElementsByTagName('description')->item(0)->nodeValue; 
    $feed->save("feed.xml"); 

?> 

所以基本上我需要獲取描述標籤,並將其保存爲XML文件。

任何幫助將不勝感激,thanx提前!

+0

請澄清是否要保存** **節點或**節點的值**。這些術語在使用DOM樹時不能用作同義詞。 – Gordon 2010-11-16 10:51:09

回答

2

幾乎正確。爲了得到一個節點的「outerXml」,您可以在節點傳遞到saveXml()

$feed = new DOMDocument(); 
$feed->load('http://www.website.com/directory/directory/cz.c'); 
$xml = $feed->saveXml($feed->getElementsByTagName('description')->item(0)); 
file_put_contents("feed.xml", $xml); 

file_put_contents保存將不包括XML序言。請注意,在您的示例中,第一個說明元素爲空,因此該文件將包含<description/>

如果你要提取的節點作爲獨立的XML文檔,你必須實例化一個新DOMDocumentimportDOMNode然後用save()

$dom = new DOMDocument($feed->xmlVersion, $feed->xmlEncoding); 
$dom->appendChild(
    $dom->importNode(
     $feed->getElementsByTagName('description')->item(0), 
     TRUE 
    ) 
); 
echo $dom->save('new.xml'); 
+0

Thanx工作,這是非常有益的,thanx很多! – Odyss3us 2010-11-16 12:59:22

0
$feed = simplexml_load_file('feed.xml'); 
$descr=$feed->channel->description; 

試試這個