PHP實現(xiàn)對xml的增刪改查操作案例分析
本文實例講述了PHP實現(xiàn)對xml的增刪改查操作。分享給大家供大家參考,具體如下:
案例:
index.php
<?php
header("content-type:text/html;charset=utf-8");
$xmldom = new DOMDocument();
$xmldom->load("demo2.xml");
//查詢學(xué)生信息
$stus = $xmldom->getElementsByTagName("學(xué)生");
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/>";
}
//添加一個學(xué)生信息
//addxml($xmldom);
function addxml($xmldom){
$root = $xmldom->getElementsByTagName("班級")->item(0);
$ostus = $xmldom->createElement_x_x("學(xué)生");
//添加屬性
$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");
}
//刪除一個學(xué)生信息
//del_element($xmldom);
function del_element($xmldom){
$dstus = $xmldom->getElementsByTagName("學(xué)生");
$laststu = $dstus->item($dstus->length-1);
$laststu->parentNode->removeChild($laststu);
}
//修改一個學(xué)生信息
//update_element($xmldom);
function update_element($xmldom){
$ustus = $xmldom->getElementsByTagName("學(xué)生");
$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:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
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
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP針對XML文件操作技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《PHP錯誤與異常處理方法總結(jié)》、《PHP基本語法入門教程》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家PHP程序設(shè)計有所幫助。
相關(guān)文章
php中通過虛代理實現(xiàn)延遲加載的實現(xiàn)代碼
基本原理是通過一個虛代理(Virtual Proxy)做占位符,一旦訪問代理對象的某成員(方法或?qū)傩裕虞d就被觸發(fā)。2011-06-06
php采集文章中的圖片獲取替換到本地(實現(xiàn)代碼)
本篇文章是對php采集文章中的圖片獲取替換到本地的實現(xiàn)代碼進行了詳細的分析介紹,需要的朋友參考下2013-07-07

