Hàm Simplexml_load_string() trong PHP
Ví dụ
Chuyển đổi một chuỗi XML thành một đối tượng, sau đó xuất ra các khóa và phần tử của đối tượng:
<?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);
?>
Chạy ví dụ »Định nghĩa và cách sử dụng
Hàm simplexml_load_string() chuyển đổi một chuỗi XML đúng định dạng thành một đối tượng.
Cú pháp
simplexml_load_string( data, class, options, ns, is_prefix )
Giá trị tham số
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 |
Chi tiết kỹ thuật
Giá trị trả về: | Một đối tượng SimpleXMLElement thành công. FALSE khi thất bại |
---|---|
Phiên bản PHP: | 5+ |
Thêm ví dụ
Ví dụ
Xuất dữ liệu từ từng phần tử trong chuỗi 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;
?>
Chạy ví dụ »Ví dụ
Xuất tên và dữ liệu của phần tử cho từng nút con trong chuỗi 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>";
}
?>
Chạy ví dụ »❮ Tham khảo PHP SimpleXML