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

相关文章

学习使用curl采集curl使用方法

复制代码 代码如下: <?php $cookie_jar = tempnam('./tmp','cookie'); $ch = curl_init(); curl_setopt($...

Ajax+PHP实现的模拟进度条功能示例

Ajax+PHP实现的模拟进度条功能示例

本文实例讲述了Ajax+PHP实现的模拟进度条功能。分享给大家供大家参考,具体如下: 一 代码 fun.js: function progress(){ setInterval(...

PHP使用file_get_contents发送http请求功能简单示例

本文实例讲述了PHP使用file_get_contents发送http请求功能。分享给大家供大家参考,具体如下: 服务器端模拟 POST/GET 等请求,使用 CURL 很容易办到(例如...

dede全站URL静态化改造[070414更正]

1、将include复制到网站中的include目录。 2、修改数据库 将所有文档设置为“仅动态”,可以进入数据库管理中,执行下面命令: update dede_archive...

php实现字符串翻转的方法

本文实例讲述了php实现字符串翻转的方法。分享给大家供大家参考。具体实现方法如下: <?php header("content-type:text/html;chars...