Home > Backend Development > PHP Problem > How to delete xml node in php

How to delete xml node in php

藏色散人
Release: 2023-03-02 11:48:01
Original
2679 people have browsed it

php method to delete xml nodes: first traverse all bird nodes and all attributes of each bird node; then modify the node value; finally delete the node through the "removeChild" method.

How to delete xml node in php

php xml reads, edits, and deletes nodes

The code is as follows:

$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>
Copy after login

For more related knowledge, please visit PHP Chinese website!

The above is the detailed content of How to delete xml node in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template