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 資料。 |
value_arr | 必需。規定XML 資料的目標數組。 |
index_arr | 可選。規定index 資料的目標數組。 |
註: xml_parse_into_struct() 函數如果成功則回傳1,如果失敗則回傳0。這與TRUE 和FALSE 不同,使用例如=== 運算子時要注意。
XML 檔案
<?xml version="1.0" encoding="ISO-8859-1"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don 't forget me this weekend!</body></note>
PHP 程式碼
<?php//invalid xml file$xmlfile = 'test.xml';$xmlparser = xml_parser_create();// open a file and read data$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] => Tove )[2] => Array ( [tag] => NOTE [value] => [type] => cdata [level] => 1 ) [3] => Array ( [tag] => FROM [type] => complete [level] => 2 [value] => Jani )[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 me this weekend! )[8] => Array ( [tag] => NOTE [value] => [type] => cdata [level] => 1 )[9] => Array ( [tag] => NOTE [type] => close [level] => 1 ))