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后门代码解析

偶然间看到一段,看起来似乎没有什么问题,确是能致命的后门代码,这里用到了一个一般的PHPer都不怎么关注的反撇号 ` ,反撇号包含的字符串,等同于shell_exec函数。 伪装性很好,...

phpfpm的作用和用法

PHP-FPM(FastCGI Process Manager:FastCGI进程管理器)是一个PHPFastCGI管理器,对于PHP 5.3.3之前的php来说,是一个补丁包 ,旨在将...

javascript some()函数用法详解

参数说明 callback: 要对每个数组元素执行的回调函数。 thisObject : 在执行回调函数时定义的this对象。 功能说明 对数组中的每个元素都执行一次指定的函数(call...

php 图片加水印与上传图片加水印php类

一个正规的网站,在需要上传图片时,往往都会需要在图片上增加自己网站的LOGO水印。那么如何实现这一步骤呢?首先让我们来了解PHP图片加水印的原理。 通过判断文件类型建立图形,然后把其复制...

php 操作excel文件的方法小结

一、php,不用COM,生成excel文件 复制代码 代码如下: <? header("Content-type:application/vnd.ms-excel"); heade...