DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
用 PHP 讀寫 XML 完全指南:DOM、SAX 與正則表達式
編輯:XML詳解     

什麼是 XML

XML 是一種資料儲存格式。它不定義存什麼資料,也不定義資料格式,只定義標記與標記的屬性。格式良好的 XML 標記長這樣:

<name>Jack Herrington</name>

不含文字的標記則寫成 <powerUp/>,也可寫成 <powerUp></powerUp>,兩者等效。標記還能帶屬性,例如:

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

特殊字元也能編碼,例如 & 寫作 &amp;。若標記對稱、字元編碼正確,文件就是「格式良好」。以下是一份圖書清單:

<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>

XML 與 HTML 都是基於標記的語言,很相似,但要注意:格式良好的 HTML 不一定是格式良好的 XML。以換行標記為例,<br> 是格式良好的 HTML,卻不是格式良好的 XML;寫成 <br/> 兩者才都成立。若想讓 HTML 同時是格式良好的 XML,可遵循 W3C 的 XHTML 標準。

用 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 載入 XML,再用 getElementsByTagName 取出指定名稱的所有元素,最後透過 nodeValue 取得節點中的文字。輸出如下:

PHP Hacks - Jack Herrington - O'Reilly
Podcasting Hacks - Jack Herrington - O'Reilly

用 SAX 解析器讀取 XML

另一種方式是使用 SAX 解析器,它運行於回呼模型:每次開啟或關閉標記、或遇到文字時,就用節點或文字資訊回呼使用者自訂的函式。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";
}
?>

可見其複雜度遠高於 DOM 版本。

用正則表達式解析 XML

我知道一提這個方法就會有工程師皺眉頭,但確實做得到。以下用 preg_ 函式讀取圖書檔:

<?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");
}
?>

缺陷在於:它不會先驗證 XML 是否格式良好,而且某些格式正確的 XML 可能與正則表達式不匹配。因此我從不建議用正則表達式讀取 XML,尤其別拿來處理直接來自使用者的 XML;只有在相容性優先、且無 DOM 與 SAX 可用時,才把它當作最後手段。

用 DOM 寫出 XML

讀取只是一半,寫出 XML 最好的方式同樣是 DOM,因為它產出的 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"
);

$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();
?>

腳本先建立 DOMDocument 並加入根節點 books,再為每本書的 author、title、publisher 建立節點與文字節點,最後用 saveXML 輸出(也可用 save 存成檔案)。

若 DOM 不可用:用 PHP 文字模板寫 XML

萬一 DOM 無法使用,也能用 PHP 文字模板拼出 XML,但問題出在實體編碼——你以為生成了完美 XML,實際使用時卻常發現某些元素沒正確編碼。為此必須對每個欄位呼叫 htmlentities:

<?php
foreach($books as $book) {
    $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
}
?>

這正是純手工拼 XML 的惱人之處。總結來說,XML 沒有想像中那麼難,尤其在 PHP 這樣的語言裡;一旦理解並正確實作,就能善用 XPath、XSLT 等強大工具。讀取來自使用者的 XML 時,請一律使用 DOM 或 SAX,別冒格式失控的風險。

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