SimpleXML 核心思想:以物件導向方式操作 XML,將所有元素轉換為物件屬性,極大簡化存取邏輯。
<?xml version="1.0" encoding="utf-8"?>
<words>
<word>
<en>boy</en>
<ch>男孩</ch>
</word>
<word>
<en>girl</en>
<ch>女孩</ch>
</word>
<word>
<en>teacher</en>
<ch>老師</ch>
</word>
<word>
<en>beauty</en>
<ch>美女</ch>
</word>
</words>
<?php
echo "<pre>";
$words = simplexml_load_file("words.xml"); // 返回物件,可用 print_r/var_dump 檢視結構
var_dump($words);
?>
<?php
echo "<pre>";
$words = simplexml_load_file("words.xml");
foreach($words->word as $row){ // $row 仍為 SimpleXMLElement 物件
print_r($row);
echo $row->ch . "<hr>"; // 直接 echo 物件屬性可輸出文字內容
}
?>
SimpleXMLElement Object
(
[en] => boy
[ch] => 男孩
)
男孩
SimpleXMLElement Object
(
[en] => girl
[ch] => 女孩
)
女孩
SimpleXMLElement Object
(
[en] => teacher
[ch] => 老師
)
老師
SimpleXML 將 XML 階層直接映射為物件屬性鏈,$words->word[0]->ch 即可精準取值,代碼可讀性極高。注意:SimpleXMLElement 物件雖可直接 echo 輸出字串,但實際類型仍為物件,若需字串操作請強制轉型 (string)$row->ch。