需要修改的xml
<?xml version="1.0"?> <config> <administration> <adminuser> <user> <id type="autoinc">1</id> <name type="username" min="3" max="20">admin</name> <passwdmd5 type="passwd" min="4" max="10">21232f297a57a5a743894a0e4a801fc3</passwdmd5> <purview type="purview">super</purview> </user> </adminuser> </administration> </config>
用php修改xml的节点
$doc = new DOMDocument; $doc->load('test.xml'); $users = $doc->documentElement->getElementsByTagName('user'); foreach($users as $user) { $purviews = $user->getElementsByTagName('purview'); $purview = $purviews->item(0); $tmpNode = $purview->cloneNode(); $tmpNode->nodeValue = "xxx"; $tmpNode = $purview->parentNode->appendChild($tmpNode); $purview->parentNode->replaceChild($tmpNode,$purview); $doc->save("test1.xml"); }
个人尝试用的simplexml 也可以修改,代码如下!,我写的较为繁琐了,不应该这样switch判断,如果有几十张 要写几十个case语句,极为不方便!
要修改此处要从 处理之前!修改xml之前就要解决!用上面的方法可以用foreach循环!应该较为方便!
private function write_xml($img_num) { //这里应该加判断xml文件是否存在,不存在就新建一个!出于给客户就已经带着xml文件,这里就不再创建! $xml = simplexml_load_file(__IMG_CONFIG__); $slider = $xml->slider; $indexad = $xml->indexad; switch($img_num) { case 'img_1': $slider->slider_1 = $img_num . '.jpg'; break; case 'img_2': $slider->slider_2 = $img_num . '.jpg'; break; case 'img_3': $slider->slider_3 = $img_num . '.jpg'; break; case 'img_4': $indexad->left = $img_num . '.jpg'; break; case 'img_5': $indexad->right = $img_num . '.jpg'; } file_put_contents(__IMG_CONFIG__, $xml->asXML()); }