PHP怎样删除xml某条数据【php问题】,php,删除,xml,数据

PHP怎样删除xml某条数据【php问题】,php,删除,xml,数据

PHP完成删除和修正xml数据的要领

example.xml

<?xml version="1.0" encoding="utf-8"?>
<root>
    <book id="1">
        <title>title1</title>
    </book>
    <book id="2">
        <title>title2</title>
    </book>
    <book id="3">
        <title>title3</title>
    </book>
    <book id="4">
        <title>title4</title>
    </book>
    <book id="5">
        <title>title5</title>
    </book>
</root>

遍历xml文档

<?php

    $doc = new DOMDocument();
    $doc->load('example.xml');

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

运转效果为:

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

修正:

<?php

    $doc = new DOMDocument();
    $doc->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 "<br>";
        }
    }
    //对文件做修正后,一定要记得从新sava一下,才修正掉原文件
    $doc -> save('example.xml');

修正后:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <book id="1">
        <title>title1</title>
    </book>
    <book id="2">
        <title>title2</title>
    </book>
    <book id="3">
        <title>33333</title>
    </book>
    <book id="4">
        <title>title4</title>
    </book>
    <book id="5">
        <title>title5</title>
    </book>
</root>

删除:

<?php

    $doc = new DOMDocument();
    $doc->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');

删除后:

<?xml version="1.0" encoding="utf-8"?>
<root>
    <book id="1">
        <title>title1</title>
    </book>
    <book id="2">
        <title>title2</title>
    </book>
    <book id="3">
        <title>33333</title>
    </book>

    <book id="5">
        <title>title5</title>
    </book>
</root>

以上内容仅供参考!

引荐教程:PHP视频教程

以上就是PHP怎样删除xml某条数据的细致内容,更多请关注ki4网别的相干文章!

分享到 :