SimpleXML 是 PHP 核心擴展之一,提供直觀的 XML 解析介面。在 CodeIgniter 專案中,封裝一個專用類別可統一處理 XML 轉換邏輯,提升代碼可維護性。
<?php
class CI_ManipulateXML {
private $xmlContent = '';
public function __construct(string $xmlContent) {
$this->xmlContent = $xmlContent;
}
/**
* 將 XML 字串轉換為 SimpleXMLElement 物件
* @return SimpleXMLElement|false 成功返回物件,失敗返回 false
*/
public function convertToObject() {
try {
// 載入 XML 字串
$xmlObject = new SimpleXMLElement($this->xmlContent);
// 檢查是否成功建立物件
if ($xmlObject === false) {
return false;
}
return $xmlObject;
} catch (Exception $e) {
// 記錄錯誤日誌(建議整合 CI 的 log_message)
log_message('error', 'XML 轉換失敗: ' . $e->getMessage());
return false;
}
}
}
?>
<?php
class Api extends CI_Controller {
public function parseXml() {
$rawXml = $this->input->raw_input_stream; // 或從檔案讀取
$this->load->library('manipulate_xml', $rawXml);
$xmlObj = $this->manipulate_xml->convertToObject();
if ($xmlObj) {
// 存取節點:$xmlObj->book[0]->title
$this->output->set_content_type('application/json')
->set_output(json_encode($xmlObj));
} else {
show_error('XML 格式錯誤', 400);
}
}
}
?>
$xmlObj->children('ns', true) 存取帶命名空間的節點$node->attributes() 獲取屬性陣列DOMXPath 進行複雜查詢libxml_use_internal_errors(true) 捕獲解析警告libxml_get_errors() 取得詳細錯誤資訊libxml_clear_errors()