PHP simplexml_load_string() 函式
示例
將一個格式正確的 XML 字串轉換為物件,然後輸出物件的鍵和元素
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
print_r($xml);
?>
執行示例 »
定義和用法
simplexml_load_string() 函式將一個格式良好的 XML 字串轉換為一個物件。
語法
simplexml_load_string(data, class, options, ns, is_prefix)
引數值
引數 | 描述 |
---|---|
data | 必需。指定一個格式良好的 XML 字串 |
類別 | 可選。指定新物件的類 |
選項 | 可選。指定額外的 Libxml 引數。透過指定選項和 1 或 0 (TRUE 或 FALSE,例如 LIBXML_NOBLANKS(1)) 來設定 可能的值
|
ns | 可選。指定一個名稱空間字首或 URI |
is_prefix | 可選。指定一個布林值。如果 ns 是字首,則為 TRUE。如果 ns 是 URI,則為 FALSE。預設為 FALSE |
技術詳情
返回值 | 成功時返回 SimpleXMLElement 物件。失敗時返回 FALSE |
---|---|
PHP 版本 | 5+ |
更多示例
示例
輸出 XML 字串中每個元素的資料
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
執行示例 »
示例
輸出 XML 字串中每個子節點元素的名稱和資料
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
echo $xml->getName() . "<br>";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br>";
}
?>
執行示例 »
❮ PHP SimpleXML 參考