Home >Backend Development >PHP Tutorial >Code sharing for recursively converting php arrays to xml

Code sharing for recursively converting php arrays to xml

高洛峰
高洛峰Original
2016-12-22 15:07:15977browse

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(&#39;a&#39;=>&#39;aaa&#39;,&#39;b&#39;=>array(&#39;c&#39;=>&#39;1234&#39; , &#39;d&#39; => "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!


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