一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

php利用正则表达式读取不规范的xml文档

时间:2014-09-19 编辑:简简单单 来源:一聚教程网

如果在你的程序中收到这样的字符串:

 代码如下 复制代码
11942268134产品1执行2013-08-12报告已出0219434368135产品2执行2013-05-12报告未出0

那么,恭喜你,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('',$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);

继续浏览有关 的文章

热门栏目