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橋接模式Bridge Pattern的優(yōu)點與實現(xiàn)過程
這篇文章主要介紹了PHP橋接模式Bridge Pattern的優(yōu)點與實現(xiàn)過程,橋接模式是一種結(jié)構(gòu)型模式,它將抽象部分與實現(xiàn)部分分離開來,使它們可以獨立地變化2023-03-03PHP使用PDO調(diào)用mssql存儲過程的方法示例
這篇文章主要介紹了PHP使用PDO調(diào)用mssql存儲過程的方法,結(jié)合簡單實例形式分析了php基于pdo簡單實現(xiàn)連接及調(diào)用存儲過程相關(guān)操作技巧,需要的朋友可以參考下2017-10-10php與XML、XSLT、Mysql的結(jié)合運用實現(xiàn)代碼
php與XML、XSLT、Mysql的結(jié)合運用實現(xiàn)代碼,需要的朋友可以參考下。2009-11-11