首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP SimpleXML 完整指南:載入、解析與巡覽 XML 文件

     編輯:PHP 綜合知識

核心函數

  • simplexml_load_file($file):從檔案/URL 載入 → SimpleXMLElement 物件。
  • simplexml_load_string($xml):從字串載入。
  • new SimpleXMLElement($file, 0, true):從檔案建立(第 3 參數 true 表 dataIsURL)。

範例 XML:books.xml

<?xml version="1.0" standalone="yes"?>
<library>
  <book>
    <title>Pride and Prejudice</title>
    <author gender="female">Jane Austen</author>
    <description>Jane Austen's most popular work.</description>
  </book>
  <book>
    <title>The Conformist</title>
    <author gender="male">Alberto Moravia</author>
    <description>Alberto Moravia's classic psyhcological novel.</description>
  </book>
  <book>
    <title>The Sun Also Rises</title>
    <author gender="male">Ernest Hemingway</author>
    <description>The masterpiece that launched Hemingway's career.</description>
  </book>
</library>

載入與結構檢視

$xml = simplexml_load_file('books.xml');
echo '<pre>';
var_dump($xml);

輸出結構:

object(SimpleXMLElement)#1 (1) {
  ["book"]=>
  array(3) {
    [0]=> object(SimpleXMLElement)#2 (3) { ["title"]=> "Pride and Prejudice", ["author"]=> "Jane Austen", ["description"]=> "..." }
    [1]=> object(SimpleXMLElement)#3 (3) { ["title"]=> "The Conformist", ["author"]=> "Alberto Moravia", ["description"]=> "..." }
    [2]=> object(SimpleXMLElement)#4 (3) { ["title"]=> "The Sun Also Rises", ["author"]=> "Ernest Hemingway", ["description"]=> "..." }
  }
}

巡覽與存取

// 迴圈所有 book
foreach ($xml->book as $book) {
    echo (string)$book->title . "\n";
    echo (string)$book->author . "\n";
    // 存取屬性
    echo (string)$book->author['gender'] . "\n";
}

// XPath 查詢
$femaleBooks = $xml->xpath('//book/author[@gender="female"]/..');
foreach ($femaleBooks as $b) {
    echo (string)$b->title . " (female author)\n";
}

// 修改並儲存
$xml->book[0]->title = 'New Title';
$xml->asXML('books_modified.xml');

常見陷阱

  • SimpleXMLElement 物件需轉型 才能正常輸出/比較:(string)$node、(int)$node。
  • 命名空間需註冊前綴:$xml->registerXPathNamespace('ns', 'https://...')。
  • 大型 XML(>100MB)會耗盡記憶體,改用 XMLReader 流式解析。
  • CDATA 區塊自動解析為文字節點,無需特殊處理。

結語

SimpleXML 以極簡 API 處理 95% XML 需求,配合 XPath 強大查詢,是 PHP 處理設定檔、API 回應、RSS/Atom 的首選工具。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved