DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
PHP 讀寫 XML 實戰:DOM、SAX 與正則表達式(上)
編輯:XML詳解     

用 PHP 讀寫 XML 聽起來可能有點可怕。老實說,XML 及其相關技術確實讓人頭痛,但「用 PHP 讀寫 XML」這件事本身並不難。先花點時間理解 XML 是什麼、拿來做什麼,接著再學幾種讀寫它的方式即可。

什麼是 XML?

XML 是一種資料儲存格式。它沒有規定該存什麼資料,也沒有規定資料的格式,它只定義了標記以及這些標記的屬性。格式良好的 XML 標記長這樣:

<name>Jack Herrington</name>

不含文字內容的標記則寫成:

<powerUp />

它與下面這種寫法完全等價:

<powerUp></powerUp>

標記也可以帶屬性,例如:

<name first="Jack" last="Herrington" />

特殊字元同樣需要編碼,例如 & 符號要寫成 &amp;。

如果一份 XML 文件的標記與屬性像範例那樣格式化,它就是「格式良好」(well-formed)——標記成對閉合、字元編碼正確。以下是格式良好 XML 的範例:

<books>
    <book>
        <author>Jack Herrington</author>
        <title>PHP Hacks</title>
        <publisher>O'Reilly</publisher>
    </book>
    <book>
        <author>Jack Herrington</author>
        <title>Podcasting Hacks</title>
        <publisher>O'Reilly</publisher>
    </book>
</books>

這份文件包含一個圖書清單:父標記 <books> 底下有一組 <book>,每個 <book> 又含有 <author>、<title> 與 <publisher>。當 XML 文件的標記結構與內容通過外部結構描述文件的驗證後,它才是「有效」(valid)的。本文只要求格式良好即可。

如果你覺得 XML 很像 HTML,那沒錯——兩者都是標記語言,有許多相似之處。但必須強調:XML 文件可能是格式良好的 HTML,但並非所有 HTML 文件都是格式良好的 XML。換行標記就是很好的例子。下面這段是格式良好的 HTML,卻不是格式良好的 XML:

<p>This is a paragraph<br>
With a line break</p>

改成這樣就兩者都成立:

<p>This is a paragraph<br />
With a line break</p>

若想把 HTML 寫成同樣格式良好的 XML,請遵循 W3C 的可擴充超文本標記語言(XHTML)標準。所有現代瀏覽器都能呈現 XHTML,而且用 XML 工具讀取 XHTML、從中找出資料,比解析 HTML 容易得多。

用 DOM 程式庫讀取 XML

讀取格式良好 XML 最簡單的方式,是使用已編入多數 PHP 安裝的文件物件模型(DOM)程式庫。DOM 會把整份文件讀進記憶體,並以節點樹表示:頂部的 books 節點有兩個 book 子節點,每本書底下各有 author、publisher、title 節點,而這些節點又各自有一個承載文字的文字子節點。

<?php
$doc = new DOMDocument();
$doc->load('books.xml');

$books = $doc->getElementsByTagName("book");
foreach ($books as $book) {
    $authors = $book->getElementsByTagName("author");
    $author = $authors->item(0)->nodeValue;

    $publishers = $book->getElementsByTagName("publisher");
    $publisher = $publishers->item(0)->nodeValue;

    $titles = $book->getElementsByTagName("title");
    $title = $titles->item(0)->nodeValue;

    echo "$title - $author - $publisher\n";
}
?>

腳本先建立 DOMDocument 物件,用 load() 載入文件;接著用 getElementsByTagName() 取得指定名稱的所有元素。在 book 節點的迴圈中,逐一取出 author、publisher、title 的 nodeValue(也就是節點中的文字)並輸出。在命令列執行:

% php e1.php
PHP Hacks - Jack Herrington - O'Reilly
Podcasting Hacks - Jack Herrington - O'Reilly

這是個不錯的起點。但如果環境中沒有 DOM 程式庫呢?

用 SAX 解析器讀取 XML

另一種方式是使用 XML Simple API(SAX)解析器,多數 PHP 安裝都內建。SAX 運作在回呼(callback)模型上:每次開啟或關閉標記、或遇到文字時,就呼叫使用者定義的函式並把節點或文字資訊傳進來。

SAX 的優點是真正輕量——解析器不會把內容長期留在記憶體,因此適合處理非常大的檔案。缺點是撰寫回呼函式相當繁瑣。

<?php
$g_books = array();
$g_elem  = null;

function startElement($parser, $name, $attrs) {
    global $g_books, $g_elem;
    if ($name == 'BOOK') $g_books[] = array();
    $g_elem = $name;
}

function endElement($parser, $name) {
    global $g_elem;
    $g_elem = null;
}

function textData($parser, $text) {
    global $g_books, $g_elem;
    if ($g_elem == 'AUTHOR' || $g_elem == 'PUBLISHER' || $g_elem == 'TITLE') {
        $g_books[count($g_books) - 1][$g_elem] = $text;
    }
}

$parser = xml_parser_create();
xml_set_element_handler($parser, "startElement", "endElement");
xml_set_character_data_handler($parser, "textData");

$f = fopen('books.xml', 'r');
while ($data = fread($f, 4096)) {
    xml_parse($parser, $data);
}
xml_parser_free($parser);

foreach ($g_books as $book) {
    echo $book['TITLE'] . " - " . $book['AUTHOR'] . " - ";
    echo $book['PUBLISHER'] . "\n";
}
?>

腳本先建立 $g_books 陣列在記憶體中存放所有圖書資訊,$g_elem 則記錄目前處理到的標記名稱。三個回呼函式中,startElement 與 endElement 分別在標記開啟與關閉時被呼叫,textData 則在兩者之間的文字上被呼叫。當 startElement 遇到 book 標記時就開啟一個新元素;textData 檢查當前元素是否為 publisher、title 或 author,若是則把文字存入目前這本書。

接著用 xml_parser_create() 建立解析器、設定回呼處理常式,然後分塊讀取檔案並送進解析器,讀完後以 xml_parser_free() 釋放資源,最後輸出陣列內容。可以明顯看出,這比 DOM 的寫法麻煩許多。

用正則表達式解析 XML

我知道提出這個方法會招來批評,但確實有人這麼做。

<?php
$xml = "";
$f = fopen('books.xml', 'r');
while ($data = fread($f, 4096)) { $xml .= $data; }
fclose($f);

preg_match_all("/<book>(.*?)<\/book>/s", $xml, $bookblocks);

foreach ($bookblocks[1] as $block) {
    preg_match_all("/<author>(.*?)<\/author>/", $block, $author);
    preg_match_all("/<title>(.*?)<\/title>/", $block, $title);
    preg_match_all("/<publisher>(.*?)<\/publisher>/", $block, $publisher);

    echo($title[1][0] . " - " . $author[1][0] . " - " . $publisher[1][0] . "\n");
}
?>

程式碼確實很短:先把檔案讀進一個大字串,用 regex 取出每個圖書區塊,再用 foreach 遍歷區塊並抽出 author、title、publisher。

問題在哪?使用正則表達式讀 XML 最大的缺陷是:它不會先檢查 XML 是否格式良好。也就是說,讀取之前你無從得知文件是否有效。而且有些格式正確的 XML 可能與你寫的正則表達式不匹配,日後還得回頭修改。

我從不建議用正則表達式讀 XML,但偶爾它是相容性最好的方案——因為正則表達式函式永遠可用。不過請絕對不要用正則表達式去讀取直接來自使用者的 XML,因為你無法控制那類文件的格式與結構。凡是來自使用者的 XML,都應該用 DOM 程式庫或 SAX 解析器處理。

用 DOM 撰寫 XML

讀取只是問題的一半,那該怎麼寫?最好的方式同樣是 DOM。

<?php
$books = array();
$books[] = array(
    'title'     => 'PHP Hacks',
    'author'    => 'Jack Herrington',
    'publisher' => "O'Reilly"
);
$books[] = array(
    'title'     => 'Podcasting Hacks',
    'author'    => 'Jack Herrington',
    'publisher' => "O'Reilly"
);

$doc = new DOMDocument();
$doc->formatOutput = true;

$r = $doc->createElement("books");
$doc->appendChild($r);

foreach ($books as $book) {
    $b = $doc->createElement("book");

    $author = $doc->createElement("author");
    $author->appendChild($doc->createTextNode($book['author']));
    $b->appendChild($author);

    $title = $doc->createElement("title");
    $title->appendChild($doc->createTextNode($book['title']));
    $b->appendChild($title);

    $publisher = $doc->createElement("publisher");
    $publisher->appendChild($doc->createTextNode($book['publisher']));
    $b->appendChild($publisher);

    $r->appendChild($b);
}

echo $doc->saveXML();
?>

腳本頂部先用範例資料填入 $books 陣列(實際情境中這些資料可能來自使用者或資料庫)。接著建立 DOMDocument、開啟 formatOutput 讓輸出便於閱讀,並把根節點 books 掛上去。然後為每本書的 author、title、publisher 建立節點與文字節點,最後把 book 節點加回根節點。結尾用 saveXML() 輸出到標準輸出(若要存成檔案,改用 save() 並指定路徑)。

使用 DOM 的真正價值在於:它產生的 XML 永遠是格式正確的。

用 PHP 直接撰寫 XML

如果 DOM 不可用,也可以用 PHP 的文字樣板來產生 XML。

<?php
$books = array();
$books[] = array(
    'title'     => 'PHP Hacks',
    'author'    => 'Jack Herrington',
    'publisher' => "O'Reilly"
);
$books[] = array(
    'title'     => 'Podcasting Hacks',
    'author'    => 'Jack Herrington',
    'publisher' => "O'Reilly"
);
?>
<books>
<?php foreach ($books as $book) { ?>
<book>
    <title><?php echo($book['title']); ?></title>
    <author><?php echo($book['author']); ?></author>
    <publisher><?php echo($book['publisher']); ?></publisher>
</book>
<?php } ?>
</books>

腳本上半部與 DOM 版本相同,下半部打開 books 標記後迭代每一本書,逐一輸出 book 及其內部的 title、author、publisher。

這種做法的麻煩之處在於實體編碼。要確保輸出正確,每個欄位都必須先呼叫 htmlentities():

<books>
<?php foreach ($books as $book) { ?>
<?php
$title     = htmlentities($book['title'], ENT_QUOTES);
$author    = htmlentities($book['author'], ENT_QUOTES);
$publisher = htmlentities($book['publisher'], ENT_QUOTES);
?>
<book>
    <title><?php echo($title); ?></title>
    <author><?php echo($author); ?></author>
    <publisher><?php echo($publisher); ?></publisher>
</book>
<?php } ?>
</books>

這就是用純 PHP 寫 XML 惱人的地方:你以為自己產生了完美的 XML,直到實際使用資料時才發現某個元素的編碼不對。

結語

XML 周圍總不缺誇大與混淆,但它其實沒有想像中那麼難——尤其是在 PHP 這樣成熟友善的語言裡。理解並正確實作 XML 之後,你會發現還有許多強大的工具可用,XPath 與 XSLT 就是其中兩個特別值得深入研究的選項。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved