PHP 5 引入 SimpleXML 擴展,讓 XML 解析變得前所未有的簡單。不再需要數百行 SAX 或 DOM 解析器代碼,只需兩行核心代碼即可完成 XML 載入與物件化。
<?xml version="1.0"?>
<news>
<story>
<headline date="January 19, 2005">Godzilla Attacks LA!</headline>
<description>Equipped with a Japanese Mind-control device...</description>
</story>
<story>
<headline date="February 14, 2006">Bigfoot Spotted at M.I.T. Dining Area</headline>
<description>The beast was seen ordering a Snapple...</description>
</story>
<story>
<headline date="May 27, 2006">London Angel Saves England</headline>
<description>The "London Angel" known only as "Kit" has saved the U.K....</description>
</story>
<story>
<headline date="June 3, 2006">Six-eyed Man to be Wed to an Eight-armed Woman</headline>
<description>Uhhhmmm... No comment really...</description>
</story>
<story>
<headline date="July 28, 2006">Ahmed's Birthday Extravaganza!</headline>
<description>The gifted youngster's birthday party should be a blast...</description>
</story>
</news>
<?php
// 1. 讀取 XML 檔案內容
$xmlFileData = file_get_contents('input.xml');
// 2. 建立 SimpleXMLElement 物件,自動解析
$xmlData = new SimpleXMLElement($xmlFileData);
// 3. 直接輸出物件結構(除錯用)
print_r($xmlData);
?>
// 取得第一則新聞標題
$firstHeadline = $xmlData->story[0]->headline;
echo $firstHeadline; // Godzilla Attacks LA!
// 取得第一則新聞的 date 屬性
$date = $xmlData->story[0]->headline['date'];
echo $date; // January 19, 2005
foreach ($xmlData->story as $story) {
echo "<h2>" . $story->headline . "</h2><br />";
echo $story->description . "<br />_________________________<br />";
echo $story->headline['date'] . "<br /><br />";
}
print_r() 輸出顯示:根元素 <news> 對應 SimpleXMLElement 物件,其 story 屬性為包含 5 個 SimpleXMLElement 物件的陣列,每個物件含 headline、description 子元素,且 headline 含 date 屬性。
| 操作 | 語法範例 |
|---|---|
| 載入 XML 字串 | new SimpleXMLElement($xmlString) |
| 載入 XML 檔案 | simplexml_load_file('file.xml') |
| 存取子元素 | $xml->childName 或 $xml->childName[0] |
| 存取屬性 | $xml->element['attrName'] |
| 遍歷同名元素 | foreach ($xml->element as $item) |
| 檢查元素是否存在 | isset($xml->element) |
| 轉回 XML 字串 | $xml->asXML() |
| XPath 查詢 | $xml->xpath('//story/headline') |
<?php
libxml_use_internal_errors(true); // 抑制預設錯誤輸出
$xml = @simplexml_load_file('input.xml');
if ($xml === false) {
$errors = libxml_get_errors();
foreach ($errors as $error) {
error_log("XML 解析錯誤:{$error->message} 第 {$error->line} 行");
}
libxml_clear_errors();
die('XML 格式錯誤');
}
// 正常處理 $xml...
?>
XMLReader(流式解析);需複雜操作(XSLT、Schema 驗證)請用 DOMDocument。