PHP,DOM - 删除前几个节点

时间:2011-10-14 18:12:48

标签: php xml dom

xml文件如下所示:

<newVotes>
    <image details="14.10.11" path="/test/content/pictures3/" image_name="PIC_524700002.jpg" id="1"/>
    <image details="14.10.11" path="/test/content/pictures3/" image_name="PIC_5317gg.jpg" id="2"/>
    <image details="14.10.11" path="/test/content/pictures3/" image_name="PIC_5393.jpg" id="3"/>
    <image details="14.10.11" path="/test/content/pictures3/" image_name="PIC_2299.jpg" id="4"/>    
    <image details="14.10.11" path="/test/content/pictures3/" image_name="PIC_4977.jpg" id="5"/>
    <image details="14.10.11" path="/test/content/pictures3/" image_name="PIC_4977BW.jpg" id="6"/>
    <image details="14.10.11" path="/test/content/pictures3/" image_name="PIC_4914.jpg" id="7"/>
    <image details="14.10.11" path="/test/content/pictures3/" image_name="flowergirl.jpg" id="8"/>
    <image details="14.10.11" path="/test/content/pictures3/" image_name="PIC_5393.jpg" id="9"/>
    <image details="14.10.11" path="/test/content/pictures3/" image_name="PIC_2299.jpg" id="10"/>
</newVotes>

我不知道有多少“图像”节点将包含我的xml,以及它们中有多少要删除(它的动态量变量来自闪存模块)我的问题是如何删除例如前5个“图像” xml中的节点,使用PHP?

Especialy添加了“id”节点,因为我认为我可以用某种方式使用Xpath删除它们,但没有幸运......

感谢您的帮助。 阿图尔。

1 个答案:

答案 0 :(得分:1)

完成......这很简单:

$filesLimit = $_POST['_limit'];
$rateElement = $news_dom->getElementsByTagName('image');
$numberOfFiles = $rateElement->length;
$m = $numberOfFiles - $filesLimit + 1;
if($numberOfFiles>=$filesLimit){         
    for ($i = 0; $i < $m; $i++) {
        $nodesToRemove = $rateElement->item(0)->parentNode->removeChild($rateElement->item(0));   
    } 
}