Code sharing for recursively converting php arrays to xml

高洛峰
Release: 2023-03-04 06:12:01
Original
892 people have browsed it

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;
}
Copy after login

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 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);
Copy after login

The result after executing the code is:

<xml><a><![CDATA[aaa]]></a><b><c><![CDATA[1234]]></c><d><![CDATA[asdfasdf]]></d></b></xml>
Copy after login

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!


Related labels:
xml
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!