本文實(shí)例講述了PHP實(shí)現(xiàn)對(duì)xml的增刪改查操作。分享給大家供大家參考,具體如下:
案例:
index.php
<?php header("content-type:text/html;charset=utf-8"); $xmldom = new DOMDocument(); $xmldom->load("demo2.xml"); //查詢(xún)學(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/>"; } //添加一個(gè)學(xué)生信息 //addxml($xmldom); function addxml($xmldom){ $root = $xmldom->getElementsByTagName("班級(jí)")->item(0); $ostus = $xmldom->createElement_x_x("學(xué)生"); //添加屬性 $ostus->setAttribute("戀愛(ài)狀況","熱戀中"); //$ostus->nodeValue="rn"; $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"); } //刪除一個(gè)學(xué)生信息 //del_element($xmldom); function del_element($xmldom){ $dstus = $xmldom->getElementsByTagName("學(xué)生"); $laststu = $dstus->item($dstus->length-1); $laststu->parentNode->removeChild($laststu); } //修改一個(gè)學(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; } //寫(xiě)會(huì)到文件中 $xmldom->save("demo2.xml"); ?>
demo2.xml
<?xml version="1.0" encoding="UTF-8"?> <班級(jí)> </班級(jí)>
PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.gimoo.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.gimoo.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.gimoo.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.gimoo.net/code/xmlcodeformat
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《PHP針對(duì)XML文件操作技巧總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《PHP錯(cuò)誤與異常處理方法總結(jié)》、《PHP基本語(yǔ)法入門(mén)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。