如果在你的程式中收到這樣的字串:
代碼如下 |
複製代碼 |
<ReportList><ordIndex>1</ordIndex><ordLabNo>1942268</ordLabNo><arcItemId>134</arcItemId><ordItemDesc>產品1</ordItemDesc><Status>執行</Status><ordDate>2013-08-12</ordDate><reportStatus>報告已出</reportStatus><reportException>0</reportException></ReportList><ReportList><ordIndex>2</ordIndex><ordLabNo>19434368</ordLabNo><arcItemId>135</arcItemId><ordItemDesc>產品2</ordItemDesc><Status>執行</Status><ordDate>2013-05-12</ordDate><reportStatus>報告未出</reportStatus><reportException>0</reportException></ReportList> |
那麼,恭喜你,php中我們常用的幾種方法
都不會生效,如:
代碼如下 |
複製代碼 |
$array = (array)new SimpleXMLElement($xml_str); $array = (array)simplexml_load_string($xml_str); $array = json_decode(json_encode(simplexml_load_string($xml_str)),true); 都是返回 false |
所以我們只能自己寫個方法嘍
代碼如下:
代碼如下 |
複製代碼 |
function parse_xml_to_array($xmlstr,$loopTag){ $args = explode('</'.$loopTag.'>',$xmlstr); $returns = array(); if($args){ $reg = '/<(\w+)[^>]*>([\x00-\xFF]*)<\/\1>/'; foreach($args as $item){ $item = str_replace('<'.$loopTag.'>','',$item); if(preg_match_all($reg, $item, $matches)) { if(isset($matches[1]) && isset($matches[2])){ $returns[] = array_combine($matches[1],$matches[2]); } } } } unset($args); return $returns; } $arr = parse_xml_to_array($xml,'ReportList'); var_dump($arr);
|
繼續瀏覽有關 的文章