SimpleXML 是 PHP 5 引入的擴展,提供極簡單的方式讀取 XML 元素名稱與文字內容。它將 XML 文檔/字串轉換為 SimpleXMLElement 物件:
適用於讀取/提取資料、修改文字節點或屬性等基礎任務。複雜命名空間、XPath 深度查詢、大型文檔建議改用 DOM 或 XMLReader。
PHP 5 起內建核心,無需安裝。
| 函數 | 說明 |
|---|---|
simplexml_load_file() | 從檔案載入 XML 並返回 SimpleXMLElement |
simplexml_load_string() | 從字串載入 XML |
simplexml_import_dom() | 從 DOMNode 轉換 |
| 方法 | 說明 |
|---|---|
__construct() | 建立物件 (通常不直接呼叫) |
addChild() | 新增子元素 |
addAttribute() | 新增屬性 |
asXML() | 輸出 XML 字串 (或存檔) |
attributes() | 取得屬性陣列 |
children() | 取得子元素 (可指定命名空間) |
xpath() | 執行 XPath 查詢 |
getName() | 取得元素名稱 |
getNamespaces() | 取得使用中的命名空間 |
count() | 子元素數量 |
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<?php
$xml = simplexml_load_file('note.xml');
print_r($xml);
/* 輸出:
SimpleXMLElement Object
(
[to] => Tove
[from] => Jani
[heading] => Reminder
[body] => Don't forget me this weekend!
)
*/
?>
<?php
$xml = simplexml_load_file('note.xml');
echo $xml->to . '<br>';
echo $xml->from . '<br>';
echo $xml->heading . '<br>';
echo $xml->body;
?>
<?php
$xml = simplexml_load_file('note.xml');
echo $xml->getName() . '<br>'; // note
foreach ($xml->children() as $child) {
echo $child->getName() . ': ' . $child . '<br>';
}
?>
<?php $xmlStr = '<book id="123"><title>PHP Guide</title></book>'; $xml = simplexml_load_string($xmlStr); echo $xml['id']; // 123 echo $xml->attributes()['id']; // 123 ?>
<?php
$xml = simplexml_load_file('note.xml');
$xml->to = 'Anna'; // 修改
$xml->addChild('date', '2024-01-15'); // 新增子元素
$xml->addAttribute('version', '1.0'); // 新增屬性
file_put_contents('note_modified.xml', $xml->asXML());
?>
<?php
$xml = simplexml_load_file('books.xml');
$results = $xml->xpath('//book[@category="php"]/title');
foreach ($results as $title) {
echo $title . '<br>';
}
?>
<?php
$xml = simplexml_load_file('namespaced.xml');
$ns = $xml->getNamespaces(true);
$xml->registerXPathNamespace('dc', $ns['dc']);
$creators = $xml->xpath('//dc:creator');
?>
XMLReader 串流解析。DOMDocument。