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中SERIALIZE和JSON的序列化与反序列化操作区别分析

本文实例讲述了PHP中SERIALIZE和JSON的序列化与反序列化操作区别。分享给大家供大家参考,具体如下: PHP中SERIALIZE和JSON序列化与反序列化区别是什么呢,对于这个...

php读取二进制流(C语言结构体struct数据文件)的深入解析

尽管php是用C语言开发的,不过令我不解的是php没有提供对结构体struct的直接支持。不过php提供了pack和unpack函数,用来进行二进制数据(binary data)和php...

php中字符查找函数strpos、strrchr与strpbrk用法

本文实例讲述了php中字符查找函数strpos、strrchr与strpbrk用法。分享给大家供大家参考。具体如下: ① strpos() 函数返回字符串在另一个字符串中第一次出现的位置...

php写app用的框架整理

PHP开发app常用的三种框架介绍 1、ThinkPHP框架 TP框架是一共快速兼容简单的轻量级国产PHP开发框架,使用面向对象的结构和MVC模式进行开发。它可以支持Windows、Li...

php跨站攻击实例分析

本文实例讲述了php跨站攻击的原理与防范技巧。分享给大家供大家参考。具体方法分析如下: 跨站攻击就是利用程序上的一些细节或bug问题进行的,那么我们要如何耿防止跨站攻击呢?下面就以一个防...