Home >Backend Development >PHP Tutorial >Code sharing for recursively converting php arrays to xml
The need to convert arrays to xml in PHP is common, and there are many implementation methods. Baidu looked for various implementation methods, but basically they borrowed some components. I wrote a string grouping method myself, which supports multi-dimensional arrays. For reference only, please feel free to let us know if there are any deficiencies!
/** * 将数组转换为xml * @param array $data 要转换的数组 * @param bool $root 是否要根节点 * @return string xml字符串 * @author Dragondean * @url http://www.cnblogs.com/dragondean */ function arr2xml($data, $root = true){ $str=""; if($root)$str .= "<xml>"; foreach($data as $key => $val){ if(is_array($val)){ $child = arr2xml($val, false); $str .= "<$key>$child</$key>"; }else{ $str.= "<$key><![CDATA[$val]]></$key>"; } } if($root)$str .= "</xml>"; return $str; }
The above is the implementation method. The first parameter is the array you want to convert. The second optional parameter sets whether you need to add the b2a0af5a8fd26276da50279a1c63a57a root node. It is required by default.
Test code:
$arr=array('a'=>'aaa','b'=>array('c'=>'1234' , 'd' => "asdfasdf")); echo arr2xml($arr);
The result after executing the code is:
<xml><a><![CDATA[aaa]]></a><b><c><![CDATA[1234]]></c><d><![CDATA[asdfasdf]]></d></b></xml>
The above is the entire content of this article, I hope you all like it.
For more code sharing related to recursively converting php arrays to xml, please pay attention to the PHP Chinese website!