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
随机推荐
- hdu 1536 S-Nim(sg函数模板)
转载自:http://blog.csdn.net/sr_19930829/article/details/23446173 解题思路: 这个题折腾了两三天,参考了两个模板,在这之间折腾过来折腾过去,终 ...
- SCREAM:Error suppression ignored for
wamp报错SCREAM:Error suppression ignored for 问题:SCREAM:Error suppression ignored for 解决: 在php.ini最下面加入 ...
- centos下安装mycat
1.在某个临时文件夹下下载mycat(此处用的是1.4 RELEASE)wget https://raw.githubusercontent.com/MyCATApache/Mycat-downloa ...
- C#使用EmguCV实现视频读取和播放,及多个视频一起播放的问题
大家知道WPF中多线程访问UI控件时会提示UI线程的数据不能直接被其他线程访问或者修改,该怎样来做呢? 分下面两种情况 1.WinForm程序 1)第一种方法,使用委托: private delega ...
- 01- 使用brew 安装ant -学习笔记(一)
1.卸载Mac OS下brew工具:ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/mast ...
- nbIoT基础概念
1. 物理信道(L1与L2之间) 上行:PRACH.PUSCH 下行:PBCH.PDCCH.PDSCH 2.逻辑信道(L2与L3之间) CCCH.DCCH.DTCH 3.信令(L3与NAS层之间) D ...
- [Java] 使用Comparator排序对象
package test.collections; import java.util.ArrayList; import java.util.Collection; import java.util. ...
- [ActionScript] AS3利用SWFObject与JS通信
首先介绍SWFObject的用法: swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flash ...
- 为什么wait(),notify()和notifyAll()必须在同步块或同步方法中调
我们常用wait(),notify()和notifyAll()方法来进行线程间通信.线程检查一个条件后就行进入等待状态,例如,在"生产者-消费者"模型中,生产者线程发现缓冲区满了就 ...
- glctx.ClearColor 参数说明
glctx.ClearColor 的参数信息如下: // ClearColor specifies the RGBA values used to clear color buffers. // // ...