Home  >  Article  >  Backend Development  >  How to delete a certain piece of xml data in PHP

How to delete a certain piece of xml data in PHP

王林
王林Original
2019-09-21 11:49:242483browse

How to delete a certain piece of xml data in PHP

PHP method to delete and modify xml data

How to delete a certain piece of xml data in PHP

##example.xml



    
        title1
    
    
        title2
    
    
        title3
    
    
        title4
    
    
        title5
    

Traverse the xml document

load('example.xml');

    $books = $doc -> getElementsByTagName("book");
    //遍历
    foreach ($books as $book) {
        echo $book->getAttribute('id')."-";
        echo $book->getElementsByTagName("title")->item(0)->nodeValue;
        echo "
"; }

The running result is:

1-title1
2-title2
3-title3
4-title4
5-title5

Modified:

load('example.xml');

    $books = $doc -> getElementsByTagName("book");
    //遍历
    foreach ($books as $book) {
        //将id=3的title设置为33333
        if($book->getAttribute('id')==3){
            echo $book->getAttribute('id')."-";
            echo $book->getElementsByTagName("title")->item(0)->nodeValue="33333";
            echo "
"; } } //对文件做修改后,一定要记得重新sava一下,才能修改掉原文件 $doc -> save('example.xml');

After modified:



    
        title1
    
    
        title2
    
    
        33333
    
    
        title4
    
    
        title5
    

Deleted:

load('example.xml');

    $root = $doc -> documentElement;//根标签   
    $books = $doc -> getElementsByTagName("book");
    //遍历
    foreach ($books as $book) {
        //将id=4的删除
        if($book->getAttribute('id')==4){
            $root->removeChild($book);
        }
    }
    //对文件做修改后,一定要记得重新sava一下,才能修改掉原文件
    $doc -> save('example.xml');

After deletion:



    
        title1
    
    
        title2
    
    
        33333
    

    
        title5
    

The above content is for reference only!


Recommended tutorial:

PHP video tutorial

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

Statement:
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