PHP xml_parse_into_struct() 函数
PHP XML Parser 函数
定义和用法
xml_parse_into_struct() 函数把 XML 数据解析到数组中。
该函数把 XML 数据解析到 2 个数组中:
- Value 数组 - 包含来自被解析的 XML 的数据
- Index 数组 - 包含指向Value 数组中值的位置的指针
如果成功,则该函数返回 1。否则返回 0。
语法
xml_parse_into_struct(parser,xml,value_arr,index_arr)
参数 | 描述 |
---|---|
parser | 必需。规定要使用的 XML 解析器。 |
xml | 必需。规定要解析的 XML 数据。 |
parser | 必需。规定 XML 数据的目标数组。 |
parser | 可选。规定 index 数据的目标数组。 |
提示和注释
注释:xml_parse_into_struct() 若失败返回 0,成功则返回 1。这和 false 与 true 不同,使用例如 === 运算符时要注意。
例子
XML 文件:
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
PHP 代码:
<?php
//无效 xml 文件
$xmlfile = 'test.xml';
$xmlparser = xml_parser_create();
// 打开文件并读取数据
$fp = fopen($xmlfile, 'r');
$xmldata = fread($fp, 4096);
xml_parse_into_struct($xmlparser,$xmldata,$values);
xml_parser_free($xmlparser);
print_r($values);
?>
//无效 xml 文件
$xmlfile = 'test.xml';
$xmlparser = xml_parser_create();
// 打开文件并读取数据
$fp = fopen($xmlfile, 'r');
$xmldata = fread($fp, 4096);
xml_parse_into_struct($xmlparser,$xmldata,$values);
xml_parser_free($xmlparser);
print_r($values);
?>
输出:
Array
(
[0] => Array
(
[tag] => NOTE
[type] => open
[level] => 1
[value] =>
)
[1] => Array
(
[tag] => TO
[type] => complete
[level] => 2
[value] => George
)
[2] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[3] => Array
(
[tag] => FROM
[type] => complete
[level] => 2
[value] => John
)
[4] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[5] => Array
(
[tag] => HEADING
[type] => complete
[level] => 2
[value] => Reminder
)
[6] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[7] => Array
(
[tag] => BODY
[type] => complete
[level] => 2
[value] => Don't forget the meeting!
)
[8] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[9] => Array
(
[tag] => NOTE
[type] => close
[level] => 1
)
)
(
[0] => Array
(
[tag] => NOTE
[type] => open
[level] => 1
[value] =>
)
[1] => Array
(
[tag] => TO
[type] => complete
[level] => 2
[value] => George
)
[2] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[3] => Array
(
[tag] => FROM
[type] => complete
[level] => 2
[value] => John
)
[4] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[5] => Array
(
[tag] => HEADING
[type] => complete
[level] => 2
[value] => Reminder
)
[6] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[7] => Array
(
[tag] => BODY
[type] => complete
[level] => 2
[value] => Don't forget the meeting!
)
[8] => Array
(
[tag] => NOTE
[value] =>
[type] => cdata
[level] => 1
)
[9] => Array
(
[tag] => NOTE
[type] => close
[level] => 1
)
)
PHP XML Parser 函数