<?php $xml=file_get_contents("c.xml"); $simple=new SimpleXMLElement($xml); //var_dump($simple); //1查询 echo "<table border='1'>"; foreach ($simple->book as $book) {$attr=$book->attributes();//获取节点属性echo "<tr>";echo "<td>".$book->name."</td>";echo "<td>".$book->price."</td>";echo "<td>".$attr['type']."</td>";echo "</tr>"; } echo "</table>";//2添加 $book=$simple->addChild('book'); $book->addChild('name',"你说是什么"); $book->addChild('price',"111"); $book->addAttribute('type',"添加语言"); $simple->saveXML("c.xml");//3替换foreach ($simple->book as $book) {$book->name.="出版设"; } //可以直接改 //$simple->book[2]->name="i"; $simple->saveXML("c.xml");//4删除 for ($i=count($simple->book)-1;$i>=0;$i--) {$currentbook=$simple->book[$i];$attr=$currentbook->attributes();if($attr['type']=='添加语言'){unset($simple->book[$i]);} } $simple->saveXML("c.xml");?>
xml
<?xml version="1.0" encoding="utf-8"?> <books> <book type="动态语言"> <name>中文版</name> <price>21</price> </book> <book type="不是语言"> <name>中文版</name> <price>21</price> </book> <book type="就态语言"> <name>中文版</name> <price>21</price> </book> <book type="动态语言"> <name>中文版</name> <price>21</price> </book> </books>