PHP simplexml_load_string() 函數
實例
轉換形式良好的 XML 字串為 SimpleXMLElement 對象,然後輸出對象的鍵和元素:
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
print_r($xml);
?>
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
print_r($xml);
?>
定義和用法
simplexml_load_string() 函數轉換形式良好的 XML 字串為 SimpleXMLElement 對象。
語法
simplexml_load_string(data,classname,options,ns,is_prefix);
參數 | 描述 |
---|---|
data | 必需。規定形式良好的 XML 字串。 |
classname | 可選。規定新對象的 class。 |
options | 可選。規定附加的 Libxml 參數。通過指定選項為 1 或 0(TRUE 或 FALSE,例如 LIBXML_NOBLANKS(1))進行設置。 可能的值:
|
ns | 可選。規定命名空間首碼或 URI。 |
is_prefix | 可選。規定一個布爾值。如果 ns 是首碼則為 TRUE,如果 ns 是 URI 則為 FALSE。默認是 FALSE。 |
技術細節
返回值: | 如果成功則返回 SimpleXMLElement 對象,如果失敗則返回 FALSE。 |
---|---|
PHP 版本: | 5+ |
更多實例
實例 1
輸出 XML 字串中每個元素的數據:
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't 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;
?>
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't 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;
?>
實例 2
輸出 XML 字串中每個子節點的元素名稱和數據:
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't 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>";
}
?>
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't 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>";
}
?>
