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>";
}
?>
運行實例»
PHP SimpleXML參考手冊