开发者

Accessing a single XML DOM Document node

I am completely new to DOM Documents, basically what I am trying to do, is to load a RSS feed in and select only one node, and then save it to a XML file.

Here is the XML I am loading from a web feed:

<?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>admin@website.com</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>

Here is my lame attempt at getting the <description> node and saving it to 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");

?>

So basically I need to get the description tag, and save it as a XML file.

Any help would be appreciated, thanx in advance!


Almost correct. To get the "outerXml" of a node, you can pass the node to 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);

Saving with file_put_contents will not include an XML prolog. Note that in your example, the first description element is empty, so the file will contain <description/>.

If you want to extract the node as standalone XML Document, you have to instantiate a new DOMDocument and import the DOMNode and then use save().

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


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

Try this

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜