将 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)
Parameter | Description |
---|---|
data | Required. Specifies a well-formed XML string |
class | Optional. Specifies the class of the new object |
options | Optional. Specifies additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1)) Possible values:
|
ns | Optional. Specifies a namespace prefix or URI |
is_prefix | Optional. Specifies a Boolean value. TRUE if ns is a prefix. FALSE if ns is a URI. Default is 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>";
}
?>
运行示例 »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!