用 SAX 方式解析 XML,得自己實作三個回呼函式,而且要靠這三個函式直接組出你要的資料結構,邏輯要求相當高。更麻煩的是,換一份結構不同的 XML,這三個函式往往得整個重寫。
改用 DOM 方式確實好些,但它把每個節點都當成一個 node,操作起來要寫的程式碼量可觀,瑣事不少。
網路上開源的 XML 解析類庫很多,看過幾個之後總覺得不踏實,好像一直在跟在別人的實作後面補洞。於是趁著換腦袋的時間,花了一天寫了一份自己的 XML 解析類——用包裝「SAX 解析結果」的方式,對外提供近似 DOM 的操作介面。就我個人而言相當實用,效能也還可以,多數處理需求都能應付。
功能:
缺點與限制:
| 連接各層節點名稱構成路徑,且必須由上而下依序書寫。程式以 PHP 5 實作,在 PHP 4 下無法正常運行。文件來不及整理,以下範例只示範一部分功能,想知道更多可以直接看原始碼。
test.php test.xml XML/ SimpleDocumentBase.php SimpleDocumentNode.php SimpleDocumentRoot.php SimpleDocumentParser.php
<?xml version="1.0" encoding="GB2312"?>
<shop>
<name>華聯</name>
<address>北京長安街-9999號</address>
<desc>連鎖超市</desc>
<cat id="food">
<goods id="food11">
<name>food11</name>
<price>12.90</price>
</goods>
<goods id="food12">
<name>food12</name>
<price>22.10</price>
<desc creator="hahawen">好東西推薦</desc>
</goods>
</cat>
<cat>
<goods id="tel21">
<name>tel21</name>
<price>1290</price>
</goods>
</cat>
<cat id="coat">
<goods id="coat31"><name>coat31</name><price>112</price></goods>
<goods id="coat32"><name>coat32</name><price>45</price></goods>
</cat>
<special id="hot">
<goods><name>hot41</name><price>99</price></goods>
</special>
</shop>
注意第二個 cat 沒有 id,程式會自動給它 cat_1 這樣的鍵名;special 裡的 goods 同樣沒有 id,會變成 goods_0。
這套設計的核心想法,是把「解析」與「操作」分開:SAX 解析器只負責把 XML 讀成樹狀物件,之後所有的查詢與修改都在這棵自造的樹上進行。
解析器持有幾個暫存狀態(目前節點、名稱、值、屬性),並在 SAX 事件中把它們組裝成物件:
class SimpleDocumentParser
{
private $domRootObject = null;
private $currentNO = null;
private $currentName = null;
private $currentValue = null;
private $currentAttribute = null;
public function getSimpleDocument()
{
return $this->domRootObject;
}
public function parse($file)
{
$xmlParser = xml_parser_create();
xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($xmlParser, XML_OPTION_SKIP_WHITE, 1);
xml_parser_set_option($xmlParser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
xml_set_object($xmlParser, $this);
xml_set_element_handler($xmlParser, 'startElement', 'endElement');
xml_set_character_data_handler($xmlParser, 'characterData');
if (!xml_parse($xmlParser, file_get_contents($file))) {
die(sprintf('XML error: %s at line %d',
xml_error_string(xml_get_error_code($xmlParser)),
xml_get_current_line_number($xmlParser)));
}
xml_parser_free($xmlParser);
}
private function startElement($parser, $name, $attrs)
{
$this->currentName = $name;
$this->currentAttribute = $attrs;
if ($this->currentNO == null) {
$this->domRootObject = new SimpleDocumentRoot($name);
$this->currentNO = $this->domRootObject;
} else {
$this->currentNO = $this->currentNO->createNode($name, $attrs);
}
}
private function endElement($parser, $name)
{
if ($this->currentName == $name) {
$tag = $this->currentNO->getSeq();
$this->currentNO = $this->currentNO->getPNodeObject();
if ($this->currentAttribute != null
&& sizeof($this->currentAttribute) > 0) {
$this->currentNO->setValue($name, array(
'value' => $this->currentValue,
'attrs' => $this->currentAttribute
));
} else {
$this->currentNO->setValue($name, $this->currentValue);
}
$this->currentNO->removeNode($tag);
} else {
$this->currentNO = is_a($this->currentNO, 'SimpleDocumentRoot')
? null
: $this->currentNO->getPNodeObject();
}
}
private function characterData($parser, $data)
{
$this->currentValue = iconv('UTF-8', 'GB2312', $data);
}
}
值得注意的三個細節:XML_OPTION_CASE_FOLDING 設為 0,保留標籤的原始大小寫;XML_OPTION_TARGET_ENCODING 設為 UTF-8,讀進來之後再用 iconv 轉成 GB2312,以對應文件本身的編碼;endElement 裡那個 $tag 暫存,是為了先回到父節點、再把值寫進父節點,最後才把暫時掛上去的節點摘掉。
這是全案的抽象基底類別,負責屬性、值、子節點三件事的存取:
abstract class SimpleDocumentBase
{
private $nodeTag = null;
private $attributes = array();
private $values = array();
private $nodes = array();
// 值操作
public function setValue($name, $value) { $this->values[$name] = $value; }
public function getValue($name = null) { ... }
public function removeValue($name) { unset($this->values["$name"]); }
// 屬性操作
public function setAttribute($name, $value) { $this->attributes[$name] = $value; }
public function getAttribute($name = null) { ... }
public function removeAttribute($name) { unset($this->attributes["$name"]); }
// 子節點:由子類別實作
public abstract function createNode($name, $attributes);
public abstract function removeNode($name);
public abstract function getNode($name = null);
// 節點鍵名的建立規則:標籤_id,缺 id 則用順序號
protected function createNodeByName($rootNodeObj, $name, $attributes, $pId)
{
$tmpObject = $rootNodeObj->createNodeObject($pId, $name, $attributes);
$key = isset($attributes['id'])
? $name . '_' . $attributes['id']
: $name . '_' . $this->getNodesSize();
$this->setNode($key, $tmpObject->getSeq());
return $tmpObject;
}
// 以 | 分隔的路徑查詢,例如 cat_food|goods_food11
public function findNodeByPath($path)
{
$pos = strpos($path, '|');
if ($pos <= 0) {
return $this->getNode($path);
}
$tmpObj = $this->getNode(substr($path, 0, $pos));
return is_object($tmpObj)
? $tmpObj->findNodeByPath(substr($path, $pos + 1))
: null;
}
// 匯出成陣列
public function getSaveData() { /* 遞迴收集 values / attrs / 子節點 */ }
// 重建 XML 文字
public function getSaveXML($level = 0) { /* 以 $level 控制縮排層級 */ }
}
findNodeByPath 是整組 API 中最實用的一個方法:它把路徑字串按 | 切開,逐層往下找,找不到就回傳 null。呼叫端因此能用一行 findNodeByPath("cat_food|goods_food11") 就定位到深層節點,不必層層 getNode()。
根節點額外多做了兩件事:一是維護一份完整的節點清單 $nodeLists,以流水號為索引,讓「建立節點物件」與「依 id 取回節點」這兩件事集中在一處;二是在輸出時負責加上 XML 宣告:
class SimpleDocumentRoot extends SimpleDocumentBase
{
private $prefixStr = '<?xml version="1.0" encoding="utf-8" ?>';
private $nodeLists = array();
public function createNodeObject($pNodeId, $name, $attributes)
{
$seq = sizeof($this->nodeLists);
$tmpObject = new SimpleDocumentNode($this, $pNodeId, $name, $seq);
$tmpObject->setAttributes($attributes);
$this->nodeLists[$seq] = $tmpObject;
return $tmpObject;
}
public function getNodeById($id) { return $this->nodeLists[$id]; }
public function removeNodeById($id) { /* ... */ }
public function getSaveXML()
{
return $this->prefixStr . "\r\n" . parent::getSaveXML(0);
}
}
而 SimpleDocumentNode 保存的是「我是誰、我爸是誰」——一個指向根物件的參照加上自己的流水號,因此它能沿著鏈往上回溯父節點:
class SimpleDocumentNode extends SimpleDocumentBase
{
private $seq = null;
private $rootObject = null;
private $pNodeId = null;
public function getPNodeObject()
{
return ($this->pNodeId == -1)
? $this->rootObject
: $this->rootObject->getNodeById($this->pNodeId);
}
// createNode / removeNode / getNode 皆委派給 rootObject 統一管理
}
把節點清單集中在根物件、子節點只存編號,是為了讓整棵樹共用同一份索引空間,避免每個節點各自維護一份子清單時容易產生的狀態不一致。
<?php
require_once 'XML/SimpleDocumentParser.php';
require_once 'XML/SimpleDocumentBase.php';
require_once 'XML/SimpleDocumentRoot.php';
require_once 'XML/SimpleDocumentNode.php';
$test = new SimpleDocumentParser();
$test->parse('test.xml');
$dom = $test->getSimpleDocument();
// 1. 匯出整份 XML 為陣列
print_r($dom->getSaveData());
// 2. 在根節點新增一個欄位
$dom->setValue('telphone', '123456789');
echo htmlspecialchars($dom->getSaveXML());
// 3. 取出某分類下的所有商品
$obj = $dom->getNode('cat_food');
$nodeList = $obj->getNode();
foreach ($nodeList as $node) {
$data = $node->getValue();
echo '商品名:' . $data['name'] . '<br>';
print_r($data);
print_r($node->getAttribute());
}
// 4. 以路徑定位單一商品
$goods = $dom->findNodeByPath('cat_food|goods_food11');
if (!is_object($goods)) {
echo '該商品不存在';
} else {
print_r($goods->getValue());
print_r($goods->getAttribute());
}
// 5. 為商品附加帶屬性的內容
$goods->setValue('leaveWord', array(
'value' => '這個商品不錯',
'attrs' => array('author' => 'hahawen', 'date' => date('Y-m-d'))
));
// 6. 修改值與刪除子節點
$g = $dom->findNodeByPath('cat_food|goods_food12');
$g->setValue('name', 'new food12');
$g->removeValue('desc');
// 7. 新增商品
$cat = $dom->findNodeByPath('cat_food');
$newObj = $cat->createNode('goods', array('id' => 'food13'));
$newObj->setValue('name', 'food13');
$newObj->setValue('price', 100);
// 8. 刪除商品
$cat->removeNode('goods_food12');
echo htmlspecialchars($dom->getSaveXML());
?>
匯出成陣列後的結構長這樣,可以看出「標籤_id」的鍵名規則如何保留了同標籤多節點的層次:
Array
(
[name] => 華聯
[address] => 北京長安街-9999號
[desc] => 連鎖超市
[cat_food] => Array
(
[attrs] => Array ( [id] => food )
[goods_food11] => Array
(
[name] => food11
[price] => 12.90
[attrs] => Array ( [id] => food11 )
)
[goods_food12] => Array
(
[name] => food12
[price] => 22.10
[desc] => Array
(
[value] => 好東西推薦
[attrs] => Array ( [creator] => hahawen )
)
[attrs] => Array ( [id] => food12 )
)
)
[cat_1] => Array ( [goods_tel21] => ... )
[cat_coat] => Array ( [goods_coat31] => ..., [goods_coat32] => ... )
[special_hot] => Array ( [goods_0] => Array ( [name] => hot41, [price] => 99 ) )
)
執行新增屬性之後,輸出的 XML 會多出這一段:
<goods id="food11"> <name>food11</name> <price>12.90</price> <leaveword author="hahawen" date="2004-12-05">這個商品不錯</leaveword> </goods>
新增商品後,cat_food 底下會多出一筆:
<goods id="food13"> <name>food13</name> <price>100</price> </goods>
刪除 goods_food12 之後,該筆資料連同它的 desc 子節點一起消失,其餘結構保持不變。
這個類別的價值不在效能或標準相容度,而在「用一份 XML 文件當資料容器」這個常見需求上,把 SAX 的囉嗦收攏成幾個好記的方法:查 getNode、按路徑查 findNodeByPath、改 setValue、加 createNode、刪 removeNode、整份倒出來 getSaveData、存回去 getSaveXML。
它也有幾個明顯的取捨值得留意:節點鍵名依賴 id 或位置編號,因此同一層級若有同標籤節點又缺乏 id,鍵名會隨刪除而改變;iconv 的編碼轉換是寫死的;輸出時並未做 XML 轉義,若值中含有 & 或 < 會產生不合法的 XML。這些都是小型內部工具可以接受、但正式專案需要補強的地方。
若今天要在 PHP 5 之後的版本上重做類似的事,SimpleXMLElement、DOMDocument 與 SQLite3 式的輕量資料層都是現成選項;而這份實作的意義,在於它把「自己想要的 API 長什麼樣子」具體地寫了出來。