PHP& DOM - 获取节点数,删除最旧节点并首先添加新节点

时间:2011-08-26 20:22:26

标签: php xml dom

我有flash照片库和简单的PHP上传器。

在uploader.php文件中,我添加了将最近添加的20张照片存储到xml文件中的代码。

我已经完成了在xml文件中保存数据的脚本,xml结构如下所示:

<images>
     <image thumb="/content/photos/tn_PICTURE1.jpg" image="/content/photos/PICTURE1.jpg" name="PICTURE1"/>
     <image thumb="/content/photos/tn_PICTURE2.jpg" image="/content/photos/PICTURE2.jpg" name="PICTURE2"/>
     <image thumb="/content/photos/tn_PICTURE3.jpg" image="/content/photos/PICTURE3.jpg" name="PICTURE3"/>
     ...
     <image thumb="/content/photos/tn_PICTURE20.jpg" image="/content/photos/PICTURE20.jpg" name="PICTURE20"/>
</images>

uploader.PHP文件的一部分:

$domtree = new DOMDocument('1.0', 'UTF-8');

$domtree->load("new_files.xml");
$root = $domtree->documentElement;
$currentImage = $domtree->createElement("image");
$currentImage = $root->appendChild($currentImage);

$thumb = $domtree->createAttribute("thumb");
$currentImage->appendChild($thumb);
$thumbValue = $domtree->createTextNode($thumbnail);
$thumb->appendChild($thumbValue);

$imagelink = $domtree->createAttribute("image");
$currentImage->appendChild($imagelink);
$imageValue = $domtree->createTextNode($fullpath);
$imagelink->appendChild($imageValue);

$imagename = $domtree->createAttribute("name");
$currentImage->appendChild($imagename);
$imagenameValue = $domtree->createTextNode($imageName);
$imagename->appendChild($imagenameValue);

$domtree->save("new_files.xml");

我想做什么?

当xml文件中超过20张图片时,我希望该脚本自动删除最后一张(最旧的),并将最新的一张作为第一张。所以结果将如下所示:

<images>
     <image thumb="/content/photos/tn_PICTURE21.jpg" image="/content/photos/PICTURE21.jpg" name="PICTURE21"/>
     <image thumb="/content/photos/tn_PICTURE1.jpg" image="/content/photos/PICTURE1.jpg" name="PICTURE1"/>
     <image thumb="/content/photos/tn_PICTURE2.jpg" image="/content/photos/PICTURE2.jpg" name="PICTURE2"/>
     ...
     <image thumb="/content/photos/tn_PICTURE19.jpg" image="/content/photos/PICTURE19.jpg" name="PICTURE19"/>
</images>

有什么建议吗?

聚苯乙烯。抱歉我的英文不好:)

此致,Artur。

1 个答案:

答案 0 :(得分:0)

为什么不使用SimpleXML对象?如果您只处理XML,它会更容易使用。

之后,您需要做的就是加载XML文件并执行以下操作:

$uploadedFilesCount = count($uploadedFiledArray);

$currentIndex = 0;
while($totalIndex < $uploadedFilesCount){
    foreach($YourSweetXMLObject->children() as $child){
        $child->attributes()->thumbs = $uploadedFiledArray[$currentIndex]['thumbs'];
        $child->attributes()->image = $uploadedFiledArray[$currentIndex]['image'];
        $child->attributes()->name = $uploadedFiledArray[$currentIndex]['name'];

        $totalIndex++;   
    }
}

唯一的问题是,如果再次上传,它将从XML对象的顶部开始。如果您希望能够从XML文件中的其他位置开始,则需要存储更多信息。

希望有所帮助。