| 
 | 
	
 
 
php有很多的编辑器来解析创建操作XML文件,现在讲解下DOMDocument是如何解析及操作XML文件的。 
  首先创建一个xml文件,代码如下 
  //如需在本页面输出xml,则添加header('content-type:application/xml'); 
//随便赋值 
$_id = '1'; 
$_title = '中国船员被杀'; 
$_content = '中国船员在泰国被杀'; 
$_author = '凤凰网'; 
$_sendtime = '2011年10月6号'; 
$_htmlpatch = '1.html'; 
#创建DOMCument对象 
$doc=new DOMDocument('1.0','utf-8'); 
#创建节点 
$news=$doc->createElement('news'); 
#创建节点 
$id=$doc->createElement('id',$_id); 
$title=$doc->createElement('title',$_title); 
$content=$doc->createElement('content',$_content); 
$summary=$doc->createElement('summary','测试'); 
$autor=$doc->createElement('author',$_author); 
$sendtime=$doc->createElement('sendtime',$_sendtime); 
#创建属性 
$msg=$doc->createAttribute('msg'); 
$value=$doc->createTextNode('不能为空'); 
$msg->appendChild($value); 
#将节点放入上级节点 
$news->appendChild($id); 
$news->appendChild($title); 
$news->appendChild($content); 
$news->appendChild($autor); 
$news->appendChild($sendtime); 
$content->appendChild($summary); 
$doc->appendChild($news); 
$title->appendChild($msg); 
#save方法保存到文件里,输出xml文件,使用saveXML方法 
$doc->save('1.xml'); 
 这个创建过程,创建了诸多节点,并且给某个节点添加属性和值。下面我们看下如何编辑XML文件的。代码如下: 
    $doc=new DOMDocument(); 
if($doc->load('1.xml')){ 
#获得根节点 
$root=$doc->documentElement; 
$title=$root->getElementsByTagName('title'); //取得节点 
foreach($title as $value){ 
//echo $value->getAttribute('type');  //获取节点属性值 
//        $value->nodeValue='fsfsfs';    //更改节点文本值 
if($value->setAttribute('type','peng')){  //更改节点属性值 
$doc->save('1.xml'); 
} 
echo $value->nodeValue; 
} 
} 
  编辑XML文件就是找到节点直接赋值就OK了,接下来,我们来操作下是如何删除节点的。我们以删除content下的summary节点为例: 
   $doc=new DOMDocument(); 
if($doc->load('1.xml')){ 
$root=$doc->documentElement; 
$content=$root->getElementsByTagName('content'); 
foreach($content as $key =>$value){ 
if($summary=$value->getElementsByTagName('summary')&& $summary!=null){ 
//$value->removeChild($summary); 
//echo $summary[]->nodeValue; 
foreach($summary as $var=>$result){ 
if($value->removeChild($result)){ 
echo '删除content下的summary成功'; 
}else{ 
echo '删除失败';  
} 
//echo $result->nodeValue; 
} 
}else{ 
echo 'content下未找到summary节点'; 
} 
} 
$doc->save('1.xml'); 
} 
  对XML文件的操作完成了,其实,php解析XML文件方法有很多种,我们只要熟练的掌握其中一种即可 |   
 
 
 
 | 
  
 |