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模拟登陆的实现方法分析

本文实例分析了php模拟登陆的实现方法。分享给大家供大家参考。具体分析如下: php模拟登陆的实现方法,这里分别列举两种方法实现模拟登陆人人网。具体实例代码如下: 1)使用snoopy模...

php内存缓存实现方法

本文实例讲述了php内存缓存实现方法。分享给大家供大家参考。具体如下: 在php中缓存分为很多种类型如,内存缓存,文件缓存,页面缓存。本文要来讲述关于php中内存缓存的一些方法,这里我们...

php中$_SERVER[PHP_SELF] 和 $_SERVER[SCRIPT_NAME]之间的区别

“PHP_SELF” 当前正在执行脚本的文件名,与 document root 相关。举例来说,在 URL 地址为 //www.jb51.net/test.php/foo.bar 的脚本...

PHP函数篇之掌握ord()与chr()函数应用

PHP函数篇之掌握ord()与chr()函数应用

中文字符编码研究系列第三期,PHP函数篇掌握ord()与 chr()函数应用,上期[PHP基础篇详解ASCII码对照表与字符转换]一文中了解了ASCII码和字符转换的方法,但使用时发现在...

php 不使用js实现页面跳转

在页面跳转的时候 一般使用都是js window.location.href 当然也可以使用复制代码 代码如下: <html> <head> <meta h...