PHP simplexml_load_file() 函數

定義和用法

simplexml_load_file() 函數把 XML 文檔載入對象中。

如果失敗,則返回 false。

語法

simplexml_load_file(file,class,options,ns,is_prefix)
參數 描述
file 必需。規定要使用的 XML 文檔。
class 可選。規定新對象的 class。
options 可選。規定附加的 Libxml 參數。
ns 可選。
is_prefix 可選。

返回值

返回類 SimpleXMLElement 的一個對象,該對象的屬性包含 XML 文檔中的數據。如果失敗,則返回 false。

實例

XML 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

PHP 代碼:

<?php
if (file_exists('test.xml'))
  {
  $xml = simplexml_load_file('test.xml');
  var_dump($xml);
  }
else
  {
  exit('Error.');
  }
?>

輸出:

object(SimpleXMLElement)#1 (4)
{
["to"]=> string(4) "George"
["from"]=> string(4) "John"
["heading"]=> string(8) "Reminder"
["body"]=> string(29) "Don't forget the meeting!"
}