PHP 5 內建擴充,將 XML 轉為物件樹,支援屬性式存取與 XPath 查詢,極適合處理 RSS、配置檔、API 回應等結構化 XML。
<?xml version="1.0" encoding="UTF-8"?>
<rss version="0.92">
<channel>
<title>Mokka mit Schlag</title>
<link>https://www.elharo.com/blog</link>
<language>en</language>
<item>
<title>Penn Station: Gone but not Forgotten</title>
<description>...</description>
<link>https://example.com/1</link>
</item>
<item>
<title>Personal for Elliotte Harold</title>
<description>...</description>
<link>https://example.com/2</link>
</item>
</channel>
</rss>
<?php
$xml = simplexml_load_file('feed.rss');
// 或字串載入
// $xml = simplexml_load_string($string);
echo "Feed 標題: {$xml->channel->title}\n";
foreach ($xml->channel->item as $item) {
echo "- {$item->title} ({$item->link})\n";
}
<?php
// 取得所有 item 標題
$titles = $xml->xpath('//item/title');
foreach ($titles as $title) {
echo $title . "\n";
}
// 依屬性過濾(若有)
// $items = $xml->xpath('//item[@category="tech"]');
<?php
$xml->channel->title = '新標題';
$xml->channel->item[0]->title = '更新後的標題';
// 儲存
$xml->asXML('feed_updated.rss');
<?php
$newItem = $xml->channel->addChild('item');
$newItem->addChild('title', '新文章');
$newItem->addChild('link', 'https://example.com/3');
$newItem->addChild('description', '內容摘要');
$xml->asXML('feed_new.rss');
<?php
$xml = new SimpleXMLElement('<root/>');
$xml->addChild('user', 'John');
$xml->user->addAttribute('id', 123);
echo $xml->asXML();
<?php
$xml = simplexml_load_file('atom.xml');
$ns = $xml->getNamespaces(true);
$entries = $xml->children($ns['atom'])->entry;
foreach ($entries as $entry) {
echo $entry->title . "\n";
}
$xml->element['attr']$xml->item[0]libxml_use_internal_errors(true) 捕獲解析錯誤SimpleXML 將整份 XML 載入記憶體,大檔案(>50MB)建議使用 XMLReader (SAX 流式解析) 或 DOMDocument 逐節點處理。