您好,欢迎访问一九零五行业门户网

PHP生成XML格式数据与解析xml数据

本文章来详细的介绍一下关于php生成xml格式数据与解析xml数据程序代码,有需要学习的朋友可参考参考,先看xml文档,代码如下:
'content1', 'pubdate' => '2009-10-11', ), array( 'title' => 'title2', 'content' => 'content2', 'pubdate' => '2009-11-11', ) ); $title_size = 1; $xml =
方法2:使用domdocument生成xml文件
创建节点使用createelement方法,创建文本内容使用createtextnode方法,添加子节点使用appendchild方法,创建属性使用createattribute方法,代码如下:
'title1', 'content' => 'content1', 'pubdate' => '2009-10-11', ), array( 'title' => 'title2', 'content' => 'content2', 'pubdate' => '2009-11-11', ) ); // 属性数组 $attribute_array = array( 'title' => array( 'size' => 1 ) ); // 创建一个xml文档并设置xml版本和编码。。 $dom=new domdocument('1.0', 'utf-8'); // 创建根节点 $article = $dom->createelement('article'); $dom->appendchild($article); foreach ($data_array as $data) { $item = $dom->createelement('item'); $article->appendchild($item); create_item($dom, $item, $data, $attribute_array); } echo $dom->savexml(); function create_item($dom, $item, $data, $attribute) { if (is_array($data)) { foreach ($data as $key => $val) { // 创建元素 $$key = $dom->createelement($key); $item->appendchild($$key); // 创建元素值 $text = $dom->createtextnode($val); $$key->appendchild($text); if (isset($attribute[$key])) { // 如果此字段存在相关属性需要设置 foreach ($attribute[$key] as $akey => $row) { // 创建属性节点 $$akey = $dom->createattribute($akey); $$key->appendchild($$akey); // 创建属性值节点 $aval = $dom->createtextnode($row); $$akey->appendchild($aval); } } // end if } } // end if } // end function ?>
下面我们以学生信息表student,需要提供给第三方调用,并有id,name,sex,age分别记录学生的姓名、性别、年龄等信息,代码如下:
create table `student` ( `id` int(11) not null auto_increment, `name` varchar(50) not null, `sex` varchar(10) not null, `age` smallint(3) not null default '0', primary key (`id`) ) engine=myisam default charset=utf8;
首先,建立createxml.php文件,先连接数据库,获取数据,代码如下:
$row['name'], 'sex' => $row['sex'], 'age' => $row['age'] ); }?>
这个时候,数据就保存在$arr中,你可以使用print_r打印下数据测试,接着,建立xml,循环数组,将数据写入到xml对应的节点中,代码如下:
formatoutput = true; $r = $doc->createelement(root); $doc->appendchild($r); foreach ($arr as $dat) { $b = $doc->createelement(data); $name = $doc->createelement(name); $name->appendchild($doc->createtextnode($dat['name'])); $b->appendchild($name); $sex = $doc->createelement(sex); $sex->appendchild($doc->createtextnode($dat['sex'])); $b->appendchild($sex); $age = $doc->createelement(age); $age->appendchild($doc->createtextnode($dat['age'])); $b->appendchild($age); $r->appendchild($b); } echo $doc->savexml();?>
我们调用了php内置的类domdocument来处理与生成xml,最终生成的xml格式,代码如下:
read()) { if ($reader->nodetype == xmlreader::text) { //判断node类型 $m = $i % 3; if ($m == 1) $name = $reader->value; //读取node值 if ($m == 2) $sex = $reader->value; if ($m == 0) { $age = $reader->value; $arr[] = array( 'name' => $name, 'sex' => $sex, 'age' => $age ); } $i++; }}//print_r($arr);?>
为了将数据name,sex和age分开,我们使用$i%3来判断取模,因为在获取的xml中,节点data下的信息是以3个子节点存在的.
生成与读取xml文档的方法有很多,下面我就不介绍了,大家可参考相关的文档.
本文地址:
转载随意,但请附上文章地址:-)
其它类似信息

推荐信息