源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

PHP基于DOM创建xml文档的方法示例

  • 时间:2021-09-11 01:31 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PHP基于DOM创建xml文档的方法示例
本文实例讲述了PHP基于DOM创建xml文档的方法。分享给大家供大家参考,具体如下: [b]DOM创建xml文档[/b] 用dom创建如下文档:
<booklist>
  <book id="1">
    <title>天龙八部</title>
    <author>金庸</author>
    <content>
      <![CDATA[ 天龙八部是金庸写的一本武侠小说,非常好看! ]]>
    </content>
  </book>
</booklist>

[b]实现步骤:[/b] 1、创建DOM对象 ——》2、创建节点——》3、创建下级节点——》4、将下级节点加入到上级节点中——》5、创建属性节点——》6、将属性节点加入到拥有该属性的节点中——》7、如果还有节点则重复2~6步骤——》8、将最高级节点(即根节点)加入到DOM对象中——》9、打开或存储xml文档。 在创建节点的过程中既可以从最下级节点开始创建,也可以从根节点开始。实现代码如下:
<?php
header('Content-Type: text/xml;');
$dom = new DOMDocument('1.0','utf-8');//建立DOM对象
$no1 = $dom->createElement('booklist');//创建普通节点:booklist
$dom->appendChild($no1);//把booklist节点加入到DOM文档中
$no2 = $dom->createElement('book');//创建book节点
$no1->appendChild($no2);//把book节点加入到booklist节点中
$no3 = $dom->createAttribute('id');//创建属性节点:id
$no3->value = 1;//给属性节点赋值
$no2->appendChild($no3);//把属性节点加入到book节点中
$no3 = $dom->createElement('title');
$no2->appendChild($no3);
$no4 = $dom->createTextNode('天龙八部');//创建文本节点:天龙八部
$no3->appendChild($no4);//把天龙八部节点加入到book节点中
$no3 = $dom->createElement('author');
$no2->appendChild($no3);
$no4 = $dom->createTextNode('金庸');//创建文本节点:天龙八部
$no3->appendChild($no4);//把天龙八部节点加入到book节点中
$no3 = $dom->createElement('content');
$no2->appendChild($no3);
$no4 = $dom->createCDATASection('天龙八部是金庸写的一本武侠小说,非常好看!');//创建文CDATA节点
$no3->appendChild($no4);//把天龙八部节点加入到book节点中
header('Content-type:text/html;charset=utf-8');
echo $dom->save('booklist.xml')?'存储成功':'存储失败';//存储为xml文档
/*直接以xml文档格式打开
header('Content-type:text/xml');
echo $dom->savexml();
*/
?>

[b]PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:[/b] [b]在线XML/JSON互相转换工具: [/b][url=http://tools.jb51.net/code/xmljson]http://tools.jb51.net/code/xmljson[/url] [b]在线格式化XML/在线压缩XML: [/b][url=http://tools.jb51.net/code/xmlformat]http://tools.jb51.net/code/xmlformat[/url] [b]XML[/b][b]在线压缩/格式化工具: [/b][url=http://tools.jb51.net/code/xml_format_compress]http://tools.jb51.net/code/xml_format_compress[/url] [b]XML[/b][b]代码在线格式化美化工具: [/b][url=http://tools.jb51.net/code/xmlcodeformat]http://tools.jb51.net/code/xmlcodeformat[/url] 更多关于PHP相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/234.htm]PHP针对XML文件操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/623.htm]PHP数组(Array)操作技巧大全[/url]》、《[url=http://www.1sucai.cn/Special/47.htm]php字符串(string)用法总结[/url]》、《[url=http://www.1sucai.cn/Special/196.htm]PHP错误与异常处理方法总结[/url]》、《[url=http://www.1sucai.cn/Special/348.htm]PHP基本语法入门教程[/url]》、《[url=http://www.1sucai.cn/Special/43.htm]php面向对象程序设计入门教程[/url]》、《[url=http://www.1sucai.cn/Special/84.htm]php+mysql数据库操作入门教程[/url]》及《[url=http://www.1sucai.cn/Special/231.htm]php常见数据库操作技巧汇总[/url]》 希望本文所述对大家PHP程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部