萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 將數組轉換為 XML 的通用類實現

前言

在 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。
  • 遞歸設計完美支持任意深度的多維數組。
  • 可通過構造函數或屬性自定義 XML 版本、編碼、根節點名稱。

擴展建議

可增加屬性支持(如 @attributes 鍵)、CDATA 區塊處理、命名空間註冊等功能,滿足更複雜的業務需求。

copyright © 萬盛學電腦網 all rights reserved