Home >Backend Development >PHP Tutorial >问一个关于xml转php 数组的问题

问一个关于xml转php 数组的问题

WBOY
WBOYOriginal
2016-06-23 14:20:14726browse

xml php

我现在要接收一个xml的内容,不是文件
接收的文件内容如下格式

?<ax>0000</ax><at>ax0000111222333442</at><ab>12345</ab><an>测试</an><ao>4021000028853283</ao><ad>20130828</ad><pmemo1>备注1</pmemo1><pmemo2>备注2</pmemo2><pmemo3>备注3</pmemo3></preq> <br> <br> <br> 怎么直接把这段代码转换为php数组,这个不是个文件,是个变量 <br> <br> <br> <h2>回复讨论(解决方案)</h2> <p class="sougouAnswer"> 在线等,希望能有人速度帮忙解决了 </p> <p class="sougouAnswer"> 找一个xml_to_array的函数 比如  <br> <br> http://www.cnblogs.com/heiing/archive/2009/12/31/1637015.html <br> <br> 然后使用它 <br> <br> <pre class="sycode" name="code"> function xml_to_array( $xml ){ $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/"; if(preg_match_all($reg, $xml, $matches)) { $count = count($matches[0]); $arr = array(); for($i = 0; $i < $count; $i++) { $key = $matches[1][$i]; $val = xml_to_array( $matches[2][$i] ); // 递归 if(array_key_exists($key, $arr)) { if(is_array($arr[$key])) { if(!array_key_exists(0,$arr[$key])) { $arr[$key] = array($arr[$key]); } }else{ $arr[$key] = array($arr[$key]); } $arr[$key][] = $val; }else{ $arr[$key] = $val; } } return $arr; }else{ return $xml; }}// Xml 转 数组, 不包括根键function xmltoarray( $xml ){ $arr = xml_to_array($xml); $key = array_keys($arr); return $arr[$key[0]];}$xml = '<?xml version="1.0" encoding="utf-8"?><pReq><ax>0000</ax><at>ax0000111222333442</at><ab>12345</ab><an>测试</an><ao>4021000028853283</ao><ad>20130828</ad><pMemo1>备注1</pMemo1><pMemo2>备注2</pMemo2><pMemo3>备注3</pMemo3></pReq>';var_export(xmltoarray($xml));

结果
array (  'ax' => '0000',  'at' => 'ax0000111222333442',  'ab' => '12345',  'an' => '测试',  'ao' => '4021000028853283',  'ad' => '20130828',  'pMemo1' => '备注1',  'pMemo2' => '备注2',  'pMemo3' => '备注3',)


据此博主说他这个函数还不够完善,请慎用

谢谢了,解决!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn