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 flv视频时间获取函数

复制代码 代码如下:<?php   function BigEndian2Int($byte_word, $signed = false) {   $int_value = 0;...

用C/C++扩展你的PHP 为你的php增加功能

用C/C++扩展你的PHP 为你的php增加功能

英文版下载: PHP 5 Power Programming https://www.jb51.net/books/61020.html PHP取得成功的一个主要原因之一是她拥有大量的可...

php中simplexml_load_file函数用法实例

本文实例讲述了php中simplexml_load_file函数用法。分享给大家供大家参考。具体用法分析如下: 在php中simplexml_load_file() 函数把 XML 文档...

ajax+php打造进度条 readyState各状态

用Ajax+php打造进度条,其实很简单。 readyState == 状态(0,1,2,3,4) 0:请求未初始化,还没调用open 1:请求已经建立,但还没有发送,还没调用send...

用PHP将网址字符串转换成超链接(网址或email)

复制代码 代码如下: function makeClickableLinks($text) { $text = eregi_replace('(((f|ht){1}tp://)[-a-z...