php xml 互相转换
正好昨天才做过类似的需求……几行代码就可以搞定。
如果你使用 curl 获取的 xml data
$xml = simplexml_load_string($data);
$data['tk'] = json_decode(json_encode($xml),TRUE);
如果是直接获取 URL 数据的话
$xml = simplexml_load_file($data);
$data['tk'] = json_decode(json_encode($xml),TRUE);
先把 simplexml 对象转换成 json,再将 json 转换成数组。
//如果乱码的话更改header函数
<?php //header('Content-type: text/html;charset=utf-8');
class xmlarray
{
private $xml = '';//用于读取xml的变量
private $data; //生成的xml
private $dom_tree;//xml目录树
/**
__construct仅用于读取xml
*/
function __construct($xml="")
{
if(empty($xml))
{
return null;
}
//$this->xml = $xml;
else
{
$this->loadxml($xml);
}
}
/**
装载要处理的xml文档也可以在初始化时装载
*/
public function loadxml($filepath)
{
$handle = @fopen($filepath,"r");
while (!feof($handle)&&$handle)
{
$xml_data .= fgets($handle, 4096);
}
$this->xml=$xml_data;
}
/**
处理xml文档
*/
private function _struct_to_array($values, &$i)
{
$child = array();
if (isset($values[$i]['value'])) array_push($child, $values[$i]['value']);
while ($i++ < count($values))
{
switch ($values[$i]['type'])
{
case 'cdata':
array_push($child, $values[$i]['value']);
break;
case 'complete':
$name = $values[$i]['tag'];
if(!empty($name))
{
$child[$name]= ($values[$i]['value'])?($values[$i]['value']):'';
if(isset($values[$i]['attributes']))
{
$child[$name] = $values[$i]['attributes'];
}
}
break;
case 'open':
$name = $values[$i]['tag'];
$size = isset($child[$name]) ? sizeof($child[$name]) : 0;
$child[$name][$size] = $this->_struct_to_array($values, $i);
break;
case 'close':
return $child;
break;
}
}
return $child;
}
/**
处理xml文档,实际调用 _struct_to_array()处理
*/
public function xml2array()
{
$xml =& $this->xml;
$values = array();
$index = array();
$array = array();
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $xml, $values, $index);
xml_parser_free($parser);
$i = 0;
$name = $values[$i]['tag'];
$array[$name] = isset($values[$i]['attributes']) ? $values[$i]['attributes'] : '';
$array[$name] = $this->_struct_to_array($values, $i);
return $array;
}
//以下为将数组转换成xml的代码 使用dom
/**
读取数组
*/
public function array2xml($array){
if(!is_array($array)){
throw new Exception('array2xml requires an array', 1);
unset($array);
}
if(!count($array)){
throw new Exception('array is empty', 2);
unset($array);
}
$this->data = new DOMDocument();
$this->dom_tree = $this->data->createElement('result');//默认要标签
$this->data->appendChild($this->dom_tree);
$this->recurse_node($array, $this->dom_tree);
}
/**
处理数组为xml
*/
private function recurse_node($data, $obj){
$i = 0;
foreach($data as $key=>$value){
if(is_array($value)){
//recurse if neccisary
$sub_obj[$i] = $this->data->createElement($key);//创建标签
$obj->appendChild($sub_obj[$i]); //将标签加入到$obj标签下
$this->recurse_node($value, $sub_obj[$i]); //将值加入此标签下
} elseif(is_object($value)) {
//no object support so just say what it is
$sub_obj[$i] = $this->data->createElement($key, 'Object: "' .
$key . '" type: "' . get_class($value) . '"');
$obj->appendChild($sub_obj[$i]);
} else {
//straight up data, no weirdness
$sub_obj[$i] = $this->data->createElement($key, $value);
//如果是最后的节点,将节点名和内容创建
$obj->appendChild($sub_obj[$i]);
}
$i++;
}
}
/**
将数组保存成xml文件
*/
public function saveXML($arraytoxml="")
{
if($arraytoxml=="")
{
$out = iconv("gbk","utf-8","请输入将要保存的文件名");
echo "<script>alert('$out')</script>";
}
else
{
return $this->data->save($arraytoxml);
}
}
}
?>
将数组转换成xml文件
<?php
$test = array(
'one'=>'number',
'two'=> array(
'c'=>1,
'd'=>2,
'e'=>3,
'f'=>4
),
'three'=>'alpha'
);
/*创建对象*/
$xmlObj= new xmlarray();
/*转换*/
$xml = $xmlObj->array2xml($test);
/*输出保存*/
$xmlObj->saveXML("a.xml");
?>
将xml解析为数组输出
<?php
/*创建对象*/
$xmlObj = new xmlarray();
/*装载*/
$xml = $xmlObj->loadxml("a.xml");
/*转换*/
$data=$xmlObj->xml2array();
/*显示*/
print_r($data);
?>
php xml 互相转换的更多相关文章
- 利用JAXB实现java实体类和xml互相转换
1.应用场景 在使用WebService实现数据上传下载,数据查询时,可以利用JAXB实现java实体类和xml互相转换 2.Demo 2.1 student.java 实体类,包含list(set同 ...
- 将Xml字符串转换成(DataTable || DataSet || XML)对象
今天用到一个功能:就是把从数据库读出来的内容转换成XML字符串流格式,并输出给一个功能函数.在写的过程,为方便以后的使用,我对这一功能进行分装.该类的具体格式如下:XmlConvert类命名空间:Ni ...
- SpringMVC关于json、xml自动转换的原理研究[附带源码分析 --转
SpringMVC关于json.xml自动转换的原理研究[附带源码分析] 原文地址:http://www.cnblogs.com/fangjian0423/p/springMVC-xml-json-c ...
- json串转化成xml文件、xml文件转换成json串
1.json串转化成xml文件 p=[{"name":"tom","age":30,"sex":"男" ...
- SpringMVC源码阅读:Json,Xml自动转换
1.前言 SpringMVC是目前J2EE平台的主流Web框架,不熟悉的园友可以看SpringMVC源码阅读入门,它交代了SpringMVC的基础知识和源码阅读的技巧 本文将通过源码(基于Spring ...
- JAXB实现java对象与xml之间转换
JAXB简介: 1.JAXB能够使用Jackson对JAXB注解的支持实现(jackson-module-jaxb-annotations),既方便生成XML,也方便生成JSON,这样一来可以更好的标 ...
- c#开发微信公众号——关于c#对象与xml的转换
在成为微信公众号开发者以后,整个交互流程:用户->微信服务器->自己的服务器->返回微信服务器->用户: 举个例子:用户在微信公众号里面发了个“您好!”,微信服务器会以特定的x ...
- C# 实现DataTable、DataSet与XML互相转换
/**//// <summary> /// 把DataSet.DataTable.DataView格式转换成XML字符串.XML文件 /// </summary> public ...
- Sql 把Xml字符串转换成一张表
分享一个Sql技巧,把xml字符串转换成一个表格 DECLARE @IdHandel INT EXEC sp_xml_preparedocument @IdHandel OUTPUT, @Bar_Ip ...
- 在线好用的json转xml超级好用在线json与xml互相转换
在线好用的json转xml超级好用在线json与xml互相转换 拿走不谢:http://www.yzcopen.com/json/jsonxmlformat
随机推荐
- 用imageROI来增加某范围的像素
//用imageROI来增加某范围的像素 //作者:sandy //时间:2015-10-5 #include <cv.h> #include <highgui.h> int ...
- Xshell5最新版激活
Xshell是一个用于MS Windows平台的强大的SSH,TELNET,和RLOGIN终端仿真软件.它使得用户能轻松和安全地从Windows PC上访问Unix/Linux主机. 以上内容全部为广 ...
- MySQL 开启与关闭远程访问&&授权前需执行GRANT USAGE ON *.* TO 'cai'@'%' IDENTIFIED BY 'caigan2015';才能终端访问
MySQL 开启与关闭远程访问 (1)通过MySQL用户去限制访问 权限系统目的: MySQL基于安全考虑root账户一般只能本地访问,但是在开发过程中可能需要打开root的远程访问权限,今天介绍的就 ...
- 30天轻松学习javaweb_Eclipse在修改了web.xml后将自动更新到tomcat服务器中
context.xml中增加<WatchedResource>WEB-INF/web.xml</WatchedResource>,Eclipse在修改了web.xml后将自动更 ...
- [Java] 过滤流BufferedInputStream和BufferedOutputStream
package test.stream; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ...
- [ActionScript 3.0] 自定义顶级类
为了结合FlashBuilder编译参数,达到发布项目时不编译trace代码方便,写一个顶级类: package { public function tracing(...args):void { C ...
- Oracle中的单行函数
Oracle中的单行函数 1 字符函数 UPPER()--将字符串转换为大写 SELECT UPPER('abc') FROM dual; LOWER()-将字符串转换为小写 SELECT LOWER ...
- C Primer Plus(第五版)3
第三章 数据和 C 在本章中你将学习下列内容: 1. 关键字: int, short, long, unsigned, char, float, double, _Bool, _Complex, _I ...
- 在Eclipse ee中成功使用jQuery UI插件
关键代码截图如下:
- [HDU 2126] Buy the souvenirs (动态规划)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2126 题意:给你n个物品,m元钱,问你最多能买个多少物品,并且有多少种解决方案. 一开始想到的是,先解 ...