这篇文章主要介绍了php基于domdocument解析和生成xml的方法,结合具体实例形式分析了php使用domdocument解析xml节点及xml文件生成的各种常用操作技巧,需要的朋友可以参考下
1. xml的生成
domdocument操作xml要比先前的simplexml要复杂一点,我觉得simplexml就想java里的dom4j,不管怎样原理都是一样的。如果把domdocument里的节点,属性看做是枝叶那么domdocument的domdocument就是根,节点和属性都挂载在这个对象下面。看看下面的代码就很清楚了
<?php
$doc=new domdocument('1.0','utf-8');
//创建根节点
$root=$doc->createelement("studentinfo");
//创建第一个子节点
$item=$doc->createelement("item");
$name=$doc->createelement("name","蔡依林");
$studentnum=$doc->createelement("num","2009010502");
//创建属性(phpdom可以把任何元素当做子节点)
$id=$doc->createattribute("id");
$value=$doc->createtextnode('1');
$id->appendchild($value);
//在父节点下面加入子节点
$item->appendchild($name);
$item->appendchild($studentnum);
$item->appendchild($id);
$item2=$doc->createelement("item");
$name2=$doc->createelement("name","潘玮柏");
$studentnum2=$doc->createelement("num","2009010505");
$id2=$doc->createattribute("id");
$value2=$doc->createtextnode('2');
$id2->appendchild($value2);
$item2->appendchild($name2);
$item2->appendchild($studentnum2);
$item2->appendchild($id2);
$root->appendchild($item);
$root->appendchild($item2);
//把根节点挂载在domdocument对象
$doc->appendchild($root);
header("content-type: text/xml");
//在页面上输出xml
echo $doc->savexml();
//将xml保存成文件
$doc->save("stu.xml");
?>
这段代码仔细看的话其实不复杂,可能性在id属性的那个地方会有点疑问,文本节点也必须挂载在domdocument下面,之后把文本节点挂载在属性下面。来看下生成的xml
其实domdocument是首先生成节点或属性,而xml的层级关系是最后通过addchild来体现的
2. domdocument解析
<?php
$doc=new domdocument();
//如果是解析xml字符串则使用loadxml
$doc->load('stu.xml');
//取得根节点
$root=$doc->documentelement;
//通过标记的名字取得对应的元素
$items=$root->getelementsbytagname('item');
foreach($items as $key=>$val){
// echo count($val->attributes);
//id是第一个属性所以使用item(0),nodevalue用来取得节点的值
echo $val->attributes->item(0)->name.":".$val->attributes->item(0)->nodevalue." ";
foreach($val->getelementsbytagname('name') as $key2=>$val2){
echo $val2->nodevalue." ";
}
foreach($val->getelementsbytagname('num') as $key3=>$val4){
echo $val4->nodevalue."</br>";
}
}
?>
解析的话重在理解,getelementsbytagname方法,attributes属性和item是解析xml的重点。别的都算简单,看看解析出来的东西
总的来说是比simplexml麻烦一些,但是作为程序员还能接受吧。
相关推荐:
php利用domdocument操作xml方法详解
php xml操作类domdocument
php 中 domdocument保存xml时中文出现乱码问题的解决方案
以上就是php实现基于domdocument解析和生成xml的方法详解的详细内容。