以下是一份可自由使用的 PHP XML 解析類別,歡迎提出改進意見。它透過 XMLTag 類別表示節點,XMLDoc 類別負責解析並建立樹狀結構。
<?PHP
//XML 中的元素
class XMLTag
{
var $parent; //父節點
var $child; //子節點
var $attribute; //本節點屬性
var $data; //本節點數據
var $TagName; //本節點名稱
var $depth; //本節點深度,根節點為 1
function XMLTag($tag='')
{
$this->attribute = array();
$this->child = array();
$this->depth = 0;
$this->parent = null;
$this->data = '';
$this->TagName = $tag;
}
function SetParent(&$parent) { $this->parent = &$parent; }
function SetAttribute($name,$value) { $this->attribute[$name] = $value; }
function AppendChild(&$child)
{
$i = count($this->child);
$this->child[$i] = &$child;
}
function GetElementsByTagName($tag)
{
$vector = array();
$tree = &$this;
$this->_GetElementByTagName($tree,$tag,$vector);
return $vector;
}
function _GetElementByTagName($tree,$tag,&$vector)
{
if($tree->TagName == $tag) array_push($vector,$tree);
$total = count($tree->child);
for($i = 0; $i < $total;$i++)
$this->_GetElementByTagName($tree->child[$i],$tag,$vector);
}
}
這個類別封裝了解析器,並在解析過程中動態建立 XML 樹:
class XMLDoc
{
var $parser; //XML 解析指針
var $XMLTree; //生成的 XML 樹
var $NowTag; //當前指向的節點
var $MaxDepth; //樹的最大深度
function XMLDoc()
{
$this->parser = XML_parser_create();
xml_parser_set_option($this->parser,XML_OPTION_CASE_FOLDING,0);
XML_set_object($this->parser,&$this);
XML_set_element_handler($this->parser,'_StartElement','_EndElement');
XML_set_character_data_handler($this->parser,'_CData');
$this->XMLTree = null;
$this->NowTag = null;
$this->MaxDepth = 0;
}
function _StartElement($parser,$element,$attribute)
{
$tag = new XMLTag();
$tag->TagName = $element;
$tag->attribute = $attribute;
if($this->XMLTree == null)
{
$tag->depth = 1;
$this->XMLTree = &$tag;
$this->NowTag = &$tag;
}
else
{
$i = count($this->NowTag->child);
$this->NowTag->child[$i] = &$tag;
$tag->parent = &$this->NowTag;
$tag->depth = $this->NowTag->depth+1;
$this->NowTag = &$tag;
}
}
function _CData($paraser,$data) { $this->NowTag->data = $data; }
function _EndElement($parser,$element)
{
$parent = &$this->NowTag->parent;
$this->NowTag = &$parent;
}
function parse()
{
if($this->XMLFile)
{
$this->XMLData = '';
while(!feof($this->XMLFile))
$this->XMLData .= fread($this->XMLFile,4096);
}
if($this->XMLData)
{
if (!xml_parse($this->parser, $this->XMLData))
{
$code = XML_get_error_code($this->parser);
$this->error = "XML error:".XML_error_string($code);
return false;
}
}
XML_parser_free($this->parser);
return true;
}
}
此外,類別還提供 JudgeEncode 判斷編碼、ChangeValueByName 與 ChangeAttrByName 修改節點、WalkTree 遞迴重建 XML、WriteToFile 寫回檔案等方法,方便在物件層級操作整份 XML 文檔。