How to convert array to xml string in php

藏色散人
Release: 2023-03-07 17:00:02
Original
2353 people have browsed it

php method to convert an array to an xml string: first create a PHP sample file; then use the "public function array2xml($arr, $level = 1) {...}" method to convert an array to An XML structured string is sufficient.

How to convert array to xml string in php

Recommended: "PHP Video Tutorial"

PHP converts an array into an XML structured string

The code is as follows:

  /**
 * 将一个数组转换为 XML 结构的字符串
 * @param array $arr 要转换的数组
 * @param int $level 节点层级, 1 为 Root.
 * @return string XML 结构的字符串
 */
public function array2xml($arr, $level = 1) {
    $s = $level == 1 ? "<xml>" : &#39;&#39;;
    foreach($arr as $tagname => $value) {
        if (is_numeric($tagname)) {
            $tagname = $value[&#39;TagName&#39;];
            unset($value[&#39;TagName&#39;]);
        }
        if(!is_array($value)) {
            $s .= "<{$tagname}>".(!is_numeric($value) ? &#39;<![CDATA[&#39; : &#39;&#39;).$value.(!is_numeric($value) ? &#39;]]>&#39; : &#39;&#39;)."</{$tagname}>";
        } else {
            $s .= "<{$tagname}>" . $this->array2xml($value, $level + 1)."</{$tagname}>";
        }
    }
    $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", &#39; &#39;, $s);
    return $level == 1 ? $s."</xml>" : $s;
}
Copy after login

The above is the detailed content of How to convert array to xml string in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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