首页  >  文章  >  后端开发  >  PHP如何删除xml某条数据

PHP如何删除xml某条数据

王林
王林原创
2019-09-21 11:49:242645浏览

PHP如何删除xml某条数据

PHP实现删除和修改xml数据的方法

xml数据.jpg

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(&#39;example.xml&#39;);

    $books = $doc -> getElementsByTagName("book");
    //遍历
    foreach ($books as $book) {
        echo $book->getAttribute(&#39;id&#39;)."-";
        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(&#39;example.xml&#39;);

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

修改后:

<?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(&#39;example.xml&#39;);

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

删除后:

<?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某条数据的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn