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.
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 ? "" : ''; foreach($arr as $tagname => $value) { if (is_numeric($tagname)) { $tagname = $value['TagName']; unset($value['TagName']); } if(!is_array($value)) { $s .= "<{$tagname}>".(!is_numeric($value) ? '' : '')."{$tagname}>"; } else { $s .= "<{$tagname}>" . $this->array2xml($value, $level + 1)."{$tagname}>"; } } $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s); return $level == 1 ? $s." " : $s; }
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!