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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

使用phpQuery采集网页的方法

phpQuery是一个基于PHP的服务端开源项目,它可以让PHP开发人员轻松处理DOM文档内容,比如获取某新闻网站的头条信息。更有意思的是,它采用了jQuery的思想,你可以像使用jQu...

PHP中cookies使用指南

综述    Cookie是在HTTP协议下,服务器或脚本可以维护客户工作站上信息的一种方式。Cookie是由Web服务器保存在用户浏览器上的小文件,它可以包含有关用户的信息(如...

请离开include_once和require_once

诚然, 这个理由是对的, 不过, 我今天要说的, 是另外一个的原因.我们知道, PHP去判断一个文件是否被加载, 是需要得到这个文件的opened_path的, 意思是说, 比如:复制代...

PHP安全性漫谈

PHP安全性漫谈

一、apache server安全性设置 1、以Nobody用户运行 一般情况下,Apache是由Root 来安装和运行的。如果Apache Server进程具有Root用户特权,那么它...

php下统计用户在线时间的一种尝试

下面列出几个比较常用的方法: 首先介绍一下所涉及的数据表结构,四个字段: 复制代码 代码如下: uid<int(10)> :用户id session_id<varcha...