PHP实现对xml的增删改查操作案例分析

yipeiwu_com6年前PHP代码库

本文实例讲述了PHP实现对xml的增删改查操作。分享给大家供大家参考,具体如下:

案例:

index.php

<?php
header("content-type:text/html;charset=utf-8");
$xmldom = new DOMDocument();
$xmldom->load("demo2.xml");
//查询学生信息
$stus = $xmldom->getElementsByTagName("学生");
for ($i=0;$i<$stus->length;$i++){
  $stu = $stus->item($i);
  getxmlnode($stu, "姓名");
  getxmlnode($stu, "年龄");
  getxmlnode($stu, "性别");
  getxmlnode($stu, "介绍");
}
function getxmlnode(&$stu,$tagname){
  echo $stuname = $stu->getElementsByTagName($tagname)->item(0)->nodeValue."<br/>";
}
//添加一个学生信息
//addxml($xmldom);
function addxml($xmldom){
  $root = $xmldom->getElementsByTagName("班级")->item(0);
  $ostus = $xmldom->createElement_x_x("学生");
  //添加属性
  $ostus->setAttribute("恋爱状况","热恋中");
  //$ostus->nodeValue="\r\n";
  $root->a($ostus);
  $ostu_name = $xmldom->createElement_x_x("姓名");
  $ostus->a($ostu_name);
  $ostu_name->nodeValue="小娜";
  $ostu_sex = $xmldom->createElement_x_x("性别");
  $ostus->a($ostu_sex);
  $ostu_sex->nodeValue="女";
  $ostu_age = $xmldom->createElement_x_x("年龄");
  $ostus->a($ostu_age);
  $ostu_age->nodeValue="23";
  $ostu_intro = $xmldom->createElement_x_x("介绍");
  $ostus->a($ostu_intro);
  $ostu_intro->nodeValue="高一美女";
  $xmldom->save("demo2.xml");
}
//删除一个学生信息
//del_element($xmldom);
function del_element($xmldom){
  $dstus = $xmldom->getElementsByTagName("学生");
  $laststu = $dstus->item($dstus->length-1);
  $laststu->parentNode->removeChild($laststu);
}
//修改一个学生信息
//update_element($xmldom);
function update_element($xmldom){
  $ustus = $xmldom->getElementsByTagName("学生");
  $ustu = $ustus->item(0);
  $ustu_age = $ustu->getElementsByTagName("年龄")->item(0);
  $ustu_age->nodeValue+=10;
}
//写会到文件中
$xmldom->save("demo2.xml");
?>

demo2.xml

<?xml version="1.0" encoding="UTF-8"?>
<班级>
</班级>

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

XML代码在线格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP针对XML文件操作技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP错误与异常处理方法总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

php接口与接口引用的深入解析

1、接口的介绍与创建 关键字 :interface 2、接口的引用与规范 关键字 :implements 接口:一种成员属性全...

PHP之变量、常量学习笔记

有关变量的传地址赋值 PHP 3 中,变量总是传值赋值。PHP 4 提供了另外一种方式给变量赋值:传地址赋值。使用传地址赋值,即简单地追加一个(&...

详解PHP实现异步调用的4种方法

浏览器和服务器之间是通过 HTTP 协议进行连接通讯的。这是一种基于请求和响应模型的协议。浏览器通过 URL 向服务器发起请求,Web 服务器接收到请求,执行一段程序,然后做出响应,发送...

php图像验证码生成代码

php图像验证码生成代码

本文实例为大家分享了php封装的一个生成图像验证码,供大家参考,具体内容如下 一、代码 index..php <!DOCTYPE html PUBLIC "-//W3C/...

php密码生成类实例

本文实例讲述了php实现的密码生成类及其应用方法,分享给大家供大家参考。具体分析如下: 一、php密码生成类功能: 1.可设定密码长度。 2.可设定要生成的密码个数,批量生成。 3.可以...