萬盛學電腦網

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

CodeIgniter 使用 SimpleXML 解析 XML 轉換為物件完整教學

前言

CodeIgniter (CI) 框架本身不內建 XML 解析庫,但 PHP 核心擴展 SimpleXML 提供了極簡單的 XML 處理能力。本文展示如何在 CI 中封裝一個可復用的 XML 操作庫,實現 XML 字串/文件到物件的雙向轉換。

核心庫類別 application/libraries/Xml_parser.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * CI XML 解析庫
 * 封裝 SimpleXML,提供容錯、編碼處理、陣列/物件雙向轉換
 */
class Xml_parser {
    protected $xmlContent;
    protected $simpleXml;
    protected $error = '';

    /**
     * 建構子:可直接傳入 XML 字串或文件路徑
     * @param string $source XML 字串或文件路徑
     * @param bool $isFile 是否為文件路徑
     */
    public function __construct(string $source = '', bool $isFile = false) {
        if ($source) $this->load($source, $isFile);
    }

    /**
     * 載入 XML 來源
     */
    public function load(string $source, bool $isFile = false): bool {
        $this->error = '';
        $this->simpleXml = null;
        
        try {
            if ($isFile) {
                if (!file_exists($source) || !is_readable($source)) {
                    throw new Exception("XML 文件不存在或不可讀:{$source}");
                }
                // 使用 simplexml_load_file 自動處理編碼聲明
                $this->simpleXml = simplexml_load_file($source, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOERROR | LIBXML_NOWARNING);
            } else {
                $this->simpleXml = simplexml_load_string($source, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOERROR | LIBXML_NOWARNING);
            }
            
            if ($this->simpleXml === false) {
                // 收集 libxml 錯誤
                $errors = libxml_get_errors();
                $this->error = implode('; ', array_map(fn($e) => "Line {$e->line}: {$e->message}", $errors));
                libxml_clear_errors();
                return false;
            }
            
            $this->xmlContent = $isFile ? file_get_contents($source) : $source;
            return true;
            
        } catch (Exception $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 獲取 SimpleXMLElement 物件(可直接操作屬性、子節點)
     */
    public function getObject(): ?SimpleXMLElement {
        return $this->simpleXml;
    }

    /**
     * 轉換為純陣列(遞歸處理屬性、子節點、CDATA)
     * @param SimpleXMLElement|null $node 內部遞歸用
     * @return array
     */
    public function toArray(?SimpleXMLElement $node = null): array {
        $node = $node ?? $this->simpleXml;
        if (!$node) return [];
        
        $arr = [];
        
        // 處理屬性
        foreach ($node->attributes() as $key => $val) {
            $arr['@attributes'][$key] = (string)$val;
        }
        
        // 處理子節點
        $children = $node->children();
        if (count($children) > 0) {
            foreach ($children as $name => $child) {
                $childArr = $this->toArray($child);
                $name = (string)$name;
                
                if (isset($arr[$name])) {
                    // 同名節點轉為索引陣列
                    if (!isset($arr[$name][0])) {
                        $arr[$name] = [$arr[$name]];
                    }
                    $arr[$name][] = $childArr;
                } else {
                    $arr[$name] = $childArr;
                }
            }
        } else {
            // 葉子節點:直接取值(含 CDATA)
            $val = trim((string)$node);
            if ($val !== '') $arr['@value'] = $val;
        }
        
        return $arr;
    }

    /**
     * 從陣列生成 XML 字串
     * @param array $data 結構:['tag' => ['@attributes'=>[], '@value'=>'', 'child'=>[]]]
     * @param string $rootElement 根元素名
     * @param string $encoding 編碼
     * @return string XML 字串
     */
    public function fromArray(array $data, string $rootElement = 'root', string $encoding = 'UTF-8'): string {
        $dom = new DOMDocument('1.0', $encoding);
        $dom->formatOutput = true;
        $root = $dom->createElement($rootElement);
        $dom->appendChild($root);
        $this->arrayToXml($dom, $root, $data);
        return $dom->saveXML();
    }

    private function arrayToXml(DOMDocument $dom, DOMElement $parent, array $data): void {
        foreach ($data as $key => $value) {
            if ($key === '@attributes') continue; // 屬性在父層處理
            if ($key === '@value') continue;      // 文本值在父層處理
            
            if (is_numeric($key)) {
                // 索引陣列:同名重複元素
                $key = 'item';
            }
            
            $child = $dom->createElement($key);
            $parent->appendChild($child);
            
            if (is_array($value)) {
                // 處理屬性
                if (isset($value['@attributes'])) {
                    foreach ($value['@attributes'] as $attrKey => $attrVal) {
                        $child->setAttribute($attrKey, $attrVal);
                    }
                }
                // 處理文本值
                if (isset($value['@value'])) {
                    $child->appendChild($dom->createTextNode($value['@value']));
                }
                // 遞歸子元素
                foreach ($value as $k => $v) {
                    if (!in_array($k, ['@attributes', '@value'], true)) {
                        $this->arrayToXml($dom, $child, [$k => $v]);
                    }
                }
            } else {
                $child->appendChild($dom->createTextNode((string)$value));
            }
        }
    }

    /**
     * 獲取最後錯誤訊息
     */
    public function getError(): string {
        return $this->error;
    }

    /**
     * 靜態快捷方法:字串轉陣列
     */
    public static function stringToArray(string $xml): array {
        $parser = new self($xml);
        return $parser->toArray();
    }
}
?>

控制器使用範例 application/controllers/Api.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('xml_parser');
    }

    /**
     * 接收 XML POST 請求,解析並返回 JSON
     */
    public function receiveXml() {
        // 獲取原始 POST 數據(application/xml 或 text/xml)
        $xmlString = file_get_contents('php://input');
        if (empty($xmlString)) {
            $this->output
                ->set_status_header(400)
                ->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'Empty XML body']));
            return;
        }

        // 解析
        if (!$this->xml_parser->load($xmlString)) {
            $this->output
                ->set_status_header(400)
                ->set_content_type('application/json')
                ->set_output(json_encode(['error' => 'XML 解析失敗: ' . $this->xml_parser->getError()]));
            return;
        }

        // 獲取物件操作
        $xmlObj = $this->xml_parser->getObject();
        $orderId = (string)$xmlObj->order->id;
        $amount = (float)$xmlObj->order->amount;
        
        // 業務邏輯...
        $result = $this->processOrder($orderId, $amount);

        // 返回 XML 回應
        $responseXml = $this->xml_parser->fromArray([
            'response' => [
                '@attributes' => ['code' => $result['code']],
                'message' => $result['msg'],
                'order_id' => $orderId,
            ]
        ], 'response');

        $this->output
            ->set_content_type('application/xml')
            ->set_output($responseXml);
    }

    /**
     * 讀取本地 XML 配置文件
     */
    public function loadConfig() {
        $configPath = APPPATH . 'config/payment_gateways.xml';
        if ($this->xml_parser->load($configPath, true)) {
            $configArray = $this->xml_parser->toArray();
            // 緩存到 CI config 或 Redis
            $this->config->set_item('payment_gateways', $configArray);
            echo "配置載入成功";
        } else {
            log_message('error', 'Payment gateway XML 載入失敗: ' . $this->xml_parser->getError());
            show_error('配置載入失敗');
        }
    }

    private function processOrder(string $id, float $amount): array {
        // 模擬業務處理
        return ['code' => 200, 'msg' => '訂單處理成功'];
    }
}
?>

配置文件範例 application/config/payment_gateways.xml

<?xml version="1.0" encoding="UTF-8"?>
<gateways>
    <gateway id="alipay" enabled="true">
        <name>支付寶</name>
        <app_id>2021000000000000</app_id>
        <public_key><![CDATA[MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...]]></public_key>
        <notify_url>https://api.example.com/pay/notify</notify_url>
    </gateway>
    <gateway id="wechat" enabled="true">
        <name>微信支付</name>
        <mch_id>1234567890</mch_id>
        <api_key><![CDATA[abcdefghijklmnopqrstuvwxyz123456]]></api_key>
    </gateway>
</gateways>

SimpleXML 常見操作速查

操作代碼說明
訪問子元素$xml->child返回 SimpleXMLElement,鏈式訪問 $xml->order->id
訪問屬性$xml['attr'] 或 $xml->attributes()['attr']返回字串或陣列
訪問文本內容(string)$xml強制轉型獲取 CDATA/文本
遍歷同名子元素foreach ($xml->items->item as $item)自動迭代
XPath 查詢$xml->xpath('//item[@id=1]')返回 SimpleXMLElement 陣列
命名空間$xml->registerXPathNamespace('ns', 'uri')配合 XPath 使用
修改值$xml->price = '99.00'直接賦值
新增子元素$xml->addChild('new', 'value')返回新元素對象
輸出 XML$xml->asXML() 或 $xml->asXML('file.xml')返回字串或寫文件

注意事項與最佳實踐

  • 編碼處理:XML 聲明編碼需與實際內容一致。SimpleXML 內部使用 UTF-8,輸入非 UTF-8 需先 `iconv`/`mb_convert_encoding` 轉碼。
  • 大文件記憶體:SimpleXML 將整個 DOM 載入記憶體。大於 50MB XML 請改用 XMLReader (SAX 流式解析) 或 libxml 事件驅動模式。
  • 命名空間:涉及命名空間時,必須用 `children('ns', true)` 或 `xpath` 配合 `registerXPathNamespace` 訪問。
  • CDATA 保留:載入時加 `LIBXML_NOCDATA` 旗標,CDATA 內容會直接作為文本節點可用 `(string)` 獲取。
  • 錯誤抑制:載入時加 `LIBXML_NOERROR | LIBXML_NOWARNING` 避免輸出到輸出流,改用 `libxml_get_errors()` 程序化處理。

總結

在 CodeIgniter 中封裝 Xml_parser 庫,統一了 XML 載入、解析、轉陣列、生成 XML 的流程,並妥善處理了編碼、錯誤、CDATA、命名空間等實戰痛點。控制器只需調用 `$this->xml_parser->load()` 即可獲得可操作的物件或陣列,極大簡化了與第三方支付、物流、ERP 等 XML 介面的對接開發。

copyright © 萬盛學電腦網 all rights reserved