Hàm xml_parse () trong PHP
❮ Tham chiếu trình phân tích cú pháp XML PHP
Thí dụ
Tạo trình phân tích cú pháp XML và phân tích cú pháp tài liệu XML ( note.xml ):
<?php
// Create an XML parser
$parser=xml_parser_create();
function char($parser,$data) {
echo $data;
}
xml_set_character_data_handler($parser,"char");
$fp=fopen("note.xml","r");
while ($data=fread($fp,4096)) {
// Parse XML data
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s
at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
xml_parser_free($parser);
fclose($fp);
?>
Định nghĩa và Cách sử dụng
Hàm xml_parse () phân tích cú pháp một tài liệu XML.
Mẹo: Để tạo trình phân tích cú pháp XML, hãy sử dụng hàm xml_parser_create () .
Cú pháp
xml_parse(parser, data, end)
Giá trị tham số
Parameter | Description |
---|---|
parser | Required. Specifies the XML parser to use |
data | Required. Specifies the data to parse |
end | Optional. If set to TRUE, the data in the data parameter is the last piece of data sent in this parse. Note: Entity errors are reported at the end of the parse - and will only show if the end parameter is TRUE |
Chi tiết kỹ thuật
Giá trị trả lại: | ĐÚNG về thành công. FALSE khi thất bại |
---|---|
Phiên bản PHP: | 4.0+ |
Các ví dụ khác
Thí dụ
Sử dụng cùng một tệp XML nhưng hiển thị dữ liệu XML theo cách khác:
<?php
$parser=xml_parser_create();
function start($parser,$element_name,$element_attrs)
{
switch($element_name) {
case "NOTE":
echo "NOTE<br>";
break;
case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}
function stop($parser,$element_name) {
echo "<br>";
}
function char($parser,$data) {
echo $data;
}
xml_set_element_handler($parser,"start","stop");
xml_set_character_data_handler($parser,"char");
$fp=fopen("note.xml","r");
while ($data=fread($fp,4096)) {
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
xml_parser_free($parser);
fclose($fp);
?>
❮ Tham chiếu trình phân tích cú pháp XML PHP