PHP数组转XML实现方法与工具
本实例详细解析了利用PHP语言将数组数据转化为XML格式的具体实现方案,旨在为相关开发者提供参考与借鉴。
具体的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);
执行上述代码后的实际输出效果如图所示:

此外,为方便后续操作,特此推荐几款常用的XML处理在线辅助工具:
支持XML与JSON格式相互转换的在线工具: 点击使用
提供XML内容在线格式化及压缩功能的工具: 点击使用
期望上述关于PHP数组转XML的内容及工具推荐,能对各位的程序设计工作产生积极帮助。