php实现将数组转换为XML的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了php实现将数组转换为XML的方法。分享给大家供大家参考。具体如下:

1. php代码如下:

<?php
class A2Xml {
 private $version = '1.0';
 private $encoding = 'UTF-8';
 private $root  = 'root';
 private $xml  = null;
 function __construct() {
  $this->xml = new XmlWriter();
 }
 function toXml($data, $eIsArray=FALSE) {
  if(!$eIsArray) {
   $this->xml->openMemory();
   $this->xml->startDocument($this->version, $this->encoding);
   $this->xml->startElement($this->root);
  }
  foreach($data as $key => $value){
 
   if(is_array($value)){
    $this->xml->startElement($key);
    $this->toXml($value, TRUE);
    $this->xml->endElement();
    continue;
   }
   $this->xml->writeElement($key, $value);
  }
  if(!$eIsArray) {
   $this->xml->endElement();
   return $this->xml->outputMemory(true);
  }
 }
}
$res = array(
 'hello' => '11212',
 'world' => '232323',
 'array' => array(
  'test' => 'test',
  'b' => array('c'=>'c', 'd'=>'d')
 ),
 'a' => 'haha'
);
$xml = new A2Xml();
echo $xml->toXml($res);

2. 运行效果如下图所示:

PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson

在线格式化XML/在线压缩XML:
http://tools.jb51.net/code/xmlformat

XML在线压缩/格式化工具:
http://tools.jb51.net/code/xml_format_compress

希望本文所述对大家的php程序设计有所帮助。

相关文章

Erlang的运算符(比较运算符,数值运算符,移位运算符,逻辑运算符)

Erlang的比较运算符 opDescription==等于/=不等于=<小于等于<小于>=大于等于>大于=:=精确的等于=/=精确的不等于等于和精确等于的区别:...

使用ucenter实现多站点同步登录的讲解

做Web开发经常会要求实现多站点同步登录的情况,对于PHP开发来说,我们可以使用ucenter来实现多个站点同时登陆同时退出,用户同步的功能。下面我们一起看一下ucenter是如何实现同...

window+nginx+php环境配置 附配置搭配说明

1,下载PHP   php下载版本比较多,其中,   vc9=vs2008编译,推荐使用IIS+php搭配模式,   vc6=vs6编译,推荐使用apache+php方式搭配,   Th...

CentOS6.5 编译安装lnmp环境

网上搜来的教程如下 复制代码 代码如下: yum -y install gcc gcc-c++ automake autoconf libtool glibc make libmcryp...

WordPress中用于获取及自定义头像图片的PHP脚本详解

get_avatar()(获取头像) get_avatar() 函数用来获取置顶邮箱或者用户的头像代码,在评论列表中非常常用。 这个函数提供一个 get_avatar 过滤器,用来过滤头...