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

源码网商城

PHP基于SimpleXML生成和解析xml的方法示例

  • 时间:2021-01-31 00:20 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:PHP基于SimpleXML生成和解析xml的方法示例
本文实例讲述了PHP基于SimpleXML生成和解析xml的方法。分享给大家供大家参考,具体如下: xml就不多解释了,php也提供了操作xml的方法,php操作xml可以有多种方式如domdocment,simplexml,xmlwriter等其中最简单的应该是simplexml了,这次就来说说simplexml怎么读取和解析xml文件或字符串 [b]1. 生成xml字符串和文件[/b]
<?php
 header("Content-type: text/html; charset=utf-8");
 $xml=new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><UsersInfo />');
 $item=$xml->addchild("item");
 $item->addchild("name","冯绍峰");
 $item->addchild("age","30");
 $item2=$xml->addchild("item");
 $item2->addchild("name","潘玮柏");
 $item2->addchild("age","29");
 $item2->addAttribute("id","02");
 header("Content-type: text/xml");
 echo $xml->asXml();
 $xml->asXml("student.xml");
?>

生成xml最重要的就是addchild,addAttribute,asXml三个方法,如果只是单纯生成xml文件的话那个header可以不要,下面是浏览器的显示结果  [img]http://files.jb51.net/file_images/article/201707/2017717115741223.jpg?2017617115850[/img] 是不是很简单呢 [b]2. simplexml解析xml文件或字符串[/b]
<?php
 header("Content-type: text/html; charset=utf-8");
 $xml=simplexml_load_file("UserInfo.xml");
 //通过children取得根节点下面的子项
 for($i=0;$i<count($xml->children());$i++){
   foreach ($xml->children()[$i] as $key => $value ) {
    echo "$key:$value"."<br/>";
   }
 }
?>

上面的方法适合解析xml文件,如果是xml字符串就把simplexml_load_file改为simplexml_load_string就可以了,children用于取得根节点或者子节点,取得的节点是一个数组直接遍历必要的时候加上过滤条件就可以了,下面是解析的结果  [img]http://files.jb51.net/file_images/article/201707/2017717115853048.jpg?2017617115944[/img] 顺便把我的xml文件贴出来
<?xml version="1.0" encoding="UTF-8"?>
<UsersInfo>
 <item>
   <name>潘玮柏</name>
   <address>上海市浦东新区</address>
   <song>快乐崇拜</song>
 </item>
 <item>
   <name>蔡依林</name>
   <address>上海市徐汇区</address>
   <song>独占神话</song>
 </item>
</UsersInfo>

总的说来操作真的太简洁了。 [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
微信版

扫一扫进微信版
返回顶部