simplexml 对xml的增删改操作
?
$fp=fopen('111.xml','w'); $xmlContent='<?xml version="1.0" encoding="utf-8" ?> '; $xmlContent.='<navlist>'; $xmlContent.='<nav id="1">'; $xmlContent.='<name>我我我</nname> '; $xmlContent.='<color>#000000</ncolor> '; $xmlContent.='</nav>'; $xmlContent.='<nav id="2">'; $xmlContent.='<name>你你你</nname> '; $xmlContent.='<color>#ffffff</ncolor> '; $xmlContent.='</nav>'; $xmlContent.='<nav id="3">'; $xmlContent.='<nname>他他他</nname> '; $xmlContent.='<ncolor>#cccccc</ncolor> '; $xmlContent.='</nav>'; $xmlContent.='</navlist>'; fwrite($fp,$xmlContent); fclose($fp); ?$fp=fopen(111.xml','w'); $xmlContent='<?xml version="1.0" encoding="utf-8" ?><navlist></navlist>'; fwrite($fp,$xmlContent); fclose($fp); $xml=simplexml_load_file('111.xml'); $app=$xml->addChild('nav'); $app->addAttribute('id',"1"); $app->addChild('name','我我我'); $app->addChild('color','#000000'); $app=$xml->addChild('nav'); $app->addAttribute('id',"2"); $app->addChild('name','你你你'); $app->addChild('color','#ffffff); $app=$xml->addChild('nav'); $app->addAttribute('id',"3"); $app->addChild('name','他他他'); $app->addChild('color','#cccccc); $xml->asXML('111.xml');?
<?xml version="1.0" encoding="utf-8"?><navlist> <nav id="1"> <name>我我我</nname> <color>#000000</ncolor> </nav> <nav id="2"> <name>你你你</nname> <color>#ffffff</ncolor> </nav> <nav id="3"> <name>他他他</nname> <color>#cccccc</ncolor> </nav></navlist>?
if($xml=simplexml_load_file('111.xml')){ foreach($xml->nav as $list){ $value[]=get_object_vars($list); } }else{ echo('load xml error!'); }?
$xml=simplexml_load_file('111.xml'); $app=$xml->addChild('nav'); $app->addAttribute('id',"4"); $app->addChild('name','它它它'); $app->addChild('color','#000000'); $xml->asXML(111.xml');?
$xml=simplexml_load_file('111.xml'); $xg=$xml->xpath("/navlist/nav[@id=‘3’]"); $xg[0]->name="他啊他啊"; $xg[0]->color="#444444"; $xml->asXML(111.xml');?
$xml=simplexml_load_file('111.xml'); unset($xml->nav[1]);$xml->asXML(111.xml');?
$xml=simplexml_load_file('111.xml'); $i=0; foreach($xml as $dup){ $sc=$dup->attributes(); if($sc['id']==2){ unset($xml->nav[$i]); } $i++; }$xml->asXML('111.xml');?
if(file_exists('111.xml')){ unlink('111.xml'); } ?