Home  >  Article  >  Backend Development  >  [PHP] Add, delete, modify and check xml study notes (2) Delete, modify and check

[PHP] Add, delete, modify and check xml study notes (2) Delete, modify and check

little bottle
little bottleforward
2019-04-17 11:22:112121browse

This article mainly introduces the implementation method of PHP's deletion, modification and query operation of xml files. It analyzes PHP's loading of xml files and the reading, modification and query of xml nodes and other related operation techniques based on specific examples. If necessary, Friends can refer to it.

xml file

<?xml version="1.0" encoding="utf-8"?>
<班级>
    <学生>
        <名字>大哈</名字>
        <年龄>30</年龄>
        <介绍>学生刻苦</介绍>
    </学生>
    <学生>
        <名字>二哈</名字>
        <年龄>35</年龄>
        <介绍>学生好</介绍>
    </学生>
    <学生 性别="男">
        <名字>哈哈</名字>
        <年龄>100</年龄>
        <介绍>这是小哈</介绍>
    </学生>
</班级>

Related tutorials: XML video tutorial

Delete

<?php
    
    //xml文件删除元素
    //1.创建DOMDocument
    $xmldoc=new DOMDocument();
    //2.加载xml文件
    $xmldoc->load("classes.xml");
    //3.找到学生节点,item(i)代表取得集合后的第i个元素
    $stu2=$xmldoc->getElementsByTagName("学生")->item(2);
    //4.找到其父节点,删除自己
    $stu2->parentNode->removeChild($stu2);
    //5.回写文件
    $xmldoc->save("classes.xml");
?>

Modify

<?php
    //xml更新
    //把第一个学生的年龄+10
    //1创建DOMDocument
    $xmldoc=new DOMDocument;
    //2加载xml文件
    $xmldoc->load("classes.xml");
    //3找到节点
    $stu1=$xmldoc->getElementsByTagName("学生")->item(0);
    //4找到年龄节点
    $stu1_age=$stu1->getElementsByTagName("年龄")->item(0);
    $stu1_age->nodeValue+=10;
    //5回写文件
    $xmldoc->save("classes.xml");
?>

Query

<?php
    
    //查询
    header("Content-type:text/html;charset=utf-8");
    //1.创建DOMDocument对象
    $xmldoc=new DOMDocument();
    //2.加载xml
    $xmldoc->load("classes.xml");
    //3.获取所有学生
    $stus=$xmldoc->getElementsByTagName("学生");
    for($i=0;$i<$stus->length;$i++){
        
        //取出每个学生的名字
        $names=$stus->item($i)->getElementsByTagName("名字");
        //取出名字的值
        echo $names->item(0)->nodeValue."<br/>";
    }
     
?>

[Related tutorials: PHP video tutorial

The above is the detailed content of [PHP] Add, delete, modify and check xml study notes (2) Delete, modify and check. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete