PHP xml_parse_into_struct() 函數(shù)
定義和用法
xml_parse_into_struct() 函數(shù)把 XML 數(shù)據(jù)解析到數(shù)組中。
該函數(shù)把 XML 數(shù)據(jù)解析到 2 個(gè)數(shù)組中:
- Value 數(shù)組 - 包含來(lái)自被解析的 XML 的數(shù)據(jù)
- Index 數(shù)組 - 包含指向Value 數(shù)組中值的位置的指針
如果成功,則該函數(shù)返回 1。否則返回 0。
語(yǔ)法
xml_parse_into_struct(parser,xml,value_arr,index_arr)
參數(shù) | 描述 |
---|---|
parser | 必需。規(guī)定要使用的 XML 解析器。 |
xml | 必需。規(guī)定要解析的 XML 數(shù)據(jù)。 |
value_arr | 必需。規(guī)定 XML 數(shù)據(jù)的目標(biāo)數(shù)組。 |
index_arr | 可選。規(guī)定 index 數(shù)據(jù)的目標(biāo)數(shù)組。 |
提示和注釋
注釋:xml_parse_into_struct() 若失敗返回 0,成功則返回 1。這和 false 與 true 不同,使用例如 === 運(yùn)算符時(shí)要注意。
例子
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
//無(wú)效 xml 文件
$xmlfile = 'test.xml';
$xmlparser = xml_parser_create();
// 打開(kāi)文件并讀取數(shù)據(jù)
$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 ) )