php如何刪除xml節點

2020-07-16 10:06:18

php刪除xml節點的方法:首先遍歷所有bird節點以及每一個bird節點的所有屬性;然後修改節點值;最後通過「removeChild」方法刪除節點即可。

php xml讀取、編輯、刪除節點

程式碼如下:

$doc = new DOMDocument();
$doc->load('bird_base.xml');
$root = $doc->getElementsByTagName('birdList');
$root = $root->item(0);
$bird = $root->getElementsByTagName('bird');
//遍歷所有 bird 節點
foreach ($bird as $rootdata) {
//遍歷每一個 bird 節點所有屬性
    $speciesID= $rootdata->getElementsByTagName('speciesID')->item(0)->nodeValue;
    $localName= $rootdata->getElementsByTagName('localName')->item(0)->nodeValue;
    $engName= $rootdata->getElementsByTagName('engName')->item(0)->nodeValue;
    $latinName= $rootdata->getElementsByTagName('latinName')->item(0)->nodeValue;
    $bird = $this->bird->get_bird_detail($speciesID);
    if(!empty($bird))
    {
        //修改節點值
        $rootdata->getElementsByTagName('localName')->item(0)->nodeValue = $bird['localName'];
        $rootdata->getElementsByTagName('engName')->item(0)->nodeValue = $bird['engName'];
        $rootdata->getElementsByTagName('latinName')->item(0)->nodeValue = $bird['latinName'];
    }else
    {
        //刪除節點
        $rootdata->parentNode->removeChild($rootdata);
    }
}
$doc->save('bird_base.xml');
bird_base.xml 範例
<?xml version="1.0" encoding="UTF-8"?>
<birdList>
<bird>
<speciesID>1</speciesID>
<localName>雪鶉</localName>
<engName>Snow Partridge</engName>
<latinName>Lerwa lerwa</latinName>
</bird>
<bird>
<speciesID>2</speciesID>
<localName>藏雪雞</localName>
<engName>Tibetan Snowcock</engName>
<latinName>Tetraogallus tibetanus</latinName>
</bird>
</birdList>

更多相關知識,請存取PHP中文網

以上就是php如何刪除xml節點的詳細內容,更多請關注TW511.COM其它相關文章!