php利用Regex讀取不規範的xml文檔

來源:互聯網
上載者:User

如果在你的程式中收到這樣的字串:

 代碼如下 複製代碼
<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);

繼續瀏覽有關 的文章

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.