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

[PHP] Add, delete, modify and check xml study notes (1) Added

little bottle
little bottleforward
2019-04-17 11:30:512798browse

This article mainly introduces the implementation method of PHP's deletion, modification and check operation of XML files. It analyzes the operation skills of PHP's addition of XML files in the form of specific examples. Friends in need can refer to it.

xml file

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

Related tutorials: xml video tutorial

Add

<?php
    
    
//增加
    //1.创建DOMDocument
    $xmldoc=new DOMDocument();
    //2.加载xml文件
    $xmldoc->load("classes.xml");
    //3.添加学生信息
    //(1)取出根节点
    $root=$xmldoc->getElementsByTagName("班级")->item(0);
    //(2)创建学生节点
    $stu_node=$xmldoc->createElement("学生");
    //添加属性节点
    $stu_node->setAttribute("性别","男");
    //(3)创建名字节点
    $stu_node_name=$xmldoc->createElement("名字");
    $stu_node_name->nodeValue="哈哈";
    //把名字节点挂载到学生节点下
    $stu_node->appendChild($stu_node_name);
    //创建年龄
    $stu_node_age=$xmldoc->createElement("年龄");
    $stu_node_age->nodeValue="100";
    $stu_node->appendChild($stu_node_age);
    //创建介绍
    $stu_node_intro=$xmldoc->createElement("介绍");
    $stu_node_intro->nodeValue="这是小哈";
    $stu_node->appendChild($stu_node_intro);
    //把学生节点挂载到根节点下
    $root->appendChild($stu_node);
    //重新保存回xml
    //如果save到源文件,则相当于是对文件更新
    //如果save是新的文件名,则连同原来文件的内容和新添加的内容都保存到新文件里
    $xmldoc->save("classes.xml");
?>

Related tutorials: PHP video tutorial

The above is the detailed content of [PHP] Add, delete, modify and check xml study notes (1) Added. 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