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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

php array_map使用自定义的函数处理数组中的每个值

array_map 将回调函数作用到给定数组的单元上。 说明 array array_map ( callable $callback , array $arr1 [, array $....

PHP开发之归档格式phar文件概念与用法详解【创建,使用,解包还原提取】

本文实例讲述了PHP开发之归档格式phar文件概念与用法。分享给大家供大家参考,具体如下: 一个php应用程序往往是由多个文件构成的,如果能把他们集中为一个文件来分发和运行是很方便的,这...

php实现数字补零的方法总结

在php中有两个函数——至少有两个是否有其他的我还不知道,能够实现数字补零,str_pad(),sprintf()详细如下 str_pad 顾名思义这个函数是针对字符串来说的这个可以对...

PHP自动生成后台导航网址的最佳方法

PHP自动生成后台导航网址的最佳方法

经常制作开发不同的网站的后台,写过很多种不同的后台导航写法。 最终积累了这种最写法,算是最好的吧。附上截图和代码如下(PHP+HTML)  复制代码 代码如下: <?ph...

PHP循环获取GET和POST值的代码

复制代码 代码如下:if(is_array($HTTP_GET_VARS))     {     &nbs...