在 API 接口開發、配置文件生成等場景中,常需將 PHP 數組轉換為標準 XML 格式。本文封裝了一個基於 XMLWriter 的通用類,支持多維數組遞歸轉換,代碼結構清晰,易於擴展。
<?php
class A2Xml {
private $version = '1.0';
private $encoding = 'UTF-8';
private $root = 'root';
private $xml = null;
public function __construct() {
$this->xml = new XMLWriter();
}
public function toXml($data, $isRecursive = false) {
if (!$isRecursive) {
$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 (!$isRecursive) {
$this->xml->endElement();
return $this->xml->outputMemory(true);
}
}
}
?>
<?php
$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 version="1.0" encoding="UTF-8"?>
<root>
<hello>11212</hello>
<world>232323</world>
<array>
<test>test</test>
<b>
<c>c</c>
<d>d</d>
</b>
</array>
<a>haha</a>
</root>
XMLWriter 逐步寫入,內存佔用低,性能優於字符串拼接。<、&),生成合法 XML。可增加屬性支持(如 @attributes 鍵)、CDATA 區塊處理、命名空間註冊等功能,滿足更複雜的業務需求。