php生成xml实例介绍



php生成xml实例介绍。利用PHP DOM应用接口如何生成一个正确的XML完整文件,并将其保存到磁盘中。生产xml文件步骤如下:

创建文档类型声明 
通常来说,XML声明放在文档顶部。PHP中声明十分简单:只要实例化一个DOM文档类的对象且赋予它一个版本号。createElement()方法用于创建节点,appendChild()方法用于创建子节点,createTextNode()方法用于赋值。
        下面是php实例代码:
<?php
header(‘Content-Type: text/plain;charset=utf-8′);
$dom = new DOMDocument(’1.0′,’utf-8′);
$root = $dom->createElement(‘oschina’);
$dom->appendChild($root);
//根节点
$catalog = $dom->createElement(‘catalog’);
$root->appendChild($catalog);
$text = $dom->createTextNode(’0′);
$catalog->appendChild($text);
//二级节点
$newsCount = $dom->createElement(‘newsCount’);
$root->appendChild($newsCount);
$text = $dom->createTextNode(’0′);
$newsCount->appendChild($text);
//二级节点
$pagesize = $dom->createElement(‘pagesize’);
$root->appendChild($pagesize);
$text = $dom->createTextNode(’20′);
$pagesize->appendChild($text);
//二级节点
$newslist = $dom->createElement(‘newslist’);
$root->appendChild($newslist);
//二级节点
$news = $dom->createElement(‘news’);
$newslist->appendChild($news);
 //三级节点
$id = $dom->createElement(‘id’);
$news->appendChild($id);
$text = $dom->createTextNode(’20′);
$id->appendChild($text);
$title = $dom->createElement(‘title’);
$news->appendChild($title);
$text = $dom->createTextNode(‘aaghfdh dh’);
$title->appendChild($text);
//三级节点的两个字段id  title
$cdata = $dom->createCDATASection(‘ Customer requests that pizza be sliced into 16 square pieces ‘);
$root->appendChild($cdata);
$pi = $dom->createProcessingInstruction(‘pizza’, ‘bake()’);
$root->appendChild($pi);
$xml_file=$dom->saveXML();
echo $xml_file;
file_put_contents(’01.xml’,$xml_file);
?>
运行效果如下:
<?xml version=”1.0″ encoding=”UTF-8″?>
-<oschina>
<catalog>0</catalog>
<newsCount>0</newsCount>
<pagesize>20</pagesize>
<newslist>
<news>
<id>20</id>
<title>aaghfdh dh</title>
</news>
</newslist>
<![CDATA[ Customer requests that pizza be sliced into 16 square pieces ]]>
<?pizza bake()?>
</oschina>