2011-08-26 85 views
0

我有一個簡單的PHP上傳器的Flash照片庫。PHP&DOM - 獲取節點數量,刪除最老的並添加一個新的

在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> 

有什麼建議嗎?

Ps。對不起,我的英文不好:)

問候,Artur。

回答

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文件的不同位置開始,那麼您將需要存儲更多信息。

希望有所幫助。