使用php从xml文件中仅读取第一个节点

时间:2012-06-24 16:05:36

标签: php xml

我正在尝试将xml数据读入php。我设法用这个scipt读取所有“标题”数据。问题是我只需要xml中的第一个“title”元素!在那一刻,我不幸地得到了所有这些。 如何只读取第一个“标题”节点?

<?php

$filename = $_SERVER['DOCUMENT_ROOT'].'images/albums/album.xml';
if (file_exists($filename)) {
$doc = new DOMDocument(); 
$doc->load($filename); 
$destinations = $doc->getElementsByTagName("title"); 

foreach ($destinations as $destination) { 
    foreach($destination->childNodes as $child) { 
        if ($child->nodeType == XML_CDATA_SECTION_NODE) { 
            echo ('<br/><strong>Värskemad pildid:</strong><br/><a      href="/images/albums/index.html" src=""/>' . $child->textContent .  '</a>');
        } 
    } 
} 

} else {
die(nothing);
}
?>

我的xml看起来像这样:

<album version="v6">
<title><![CDATA[2012-06-06 NK maakondlik laager]]></title>

<slide>
    <title><![CDATA[2012 NK maakondlik laager 003]]></title>

<description><![CDATA[text here]]></description>
        <date>05.06.2012 19:12</date>

    <image width="1069" height="813">slides/2012 NK maakondlik laager 003.JPG</image>
    <thumb width="240" height="180">thumbs/2012 NK maakondlik laager 003.JPG</thumb>
<info filesize="3.84 MB" date="05.06.2012 19:12" resolution="3456 x 2592 px" flash="Flash did not fire, auto" focus="5.0mm" 
exposure="1/320s" aperture="3.4" distance="" metering="Center weighted average" 
cameramake="Panasonic" cameramodel="DMC-TZ5" camera="DMC-TZ5" sensor="OneChipColorArea" iso="100"/>
</slide>


<slide>
    <title><![CDATA[2012 NK maakondlik laager 004]]></title>

<description><![CDATA[text here]]></description>
    <date>05.06.2012 19:22</date>

    <image width="1069" height="813">slides/2012 NK maakondlik laager 004.JPG</image>
    <thumb width="240" height="180">thumbs/2012 NK maakondlik laager 004.JPG</thumb>
<info filesize="4.07 MB" date="05.06.2012 19:22" resolution="3456 x 2592 px" flash="Flash did not fire, auto" focus="5.0mm" 
exposure="1/250s" aperture="3.4" distance="" metering="Center weighted average" 
cameramake="Panasonic" cameramodel="DMC-TZ5" camera="DMC-TZ5" sensor="OneChipColorArea" iso="100"/>
</slide>

1 个答案:

答案 0 :(得分:0)

尝试:

<?php
$filename = $_SERVER['DOCUMENT_ROOT'].'images/albums/album.xml';
if (file_exists($filename)) {
$xml = simplexml_load_file($filename);
echo $xml->title[0];
} else {
die("nothing");
}
?>
相关问题