Home >Backend Development >PHP Problem >How to convert array to xml in php

How to convert array to xml in php

藏色散人
藏色散人Original
2021-07-14 10:17:363317browse

php method to convert array to xml: first create a PHP sample file; then convert the array to xml format through the "function data_to_xml($data) {...}" method.

How to convert array to xml in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How does php convert an array to xml?

php Convert the array to xml format

php Convert the array to xml format, excerpted from thinkphp, record it

/**
 * XML编码
 * @param mixed $data 数据
 * @param string $encoding 数据编码
 * @param string $root 根节点名
 * @return string
 */
function xml_encode($data, $encoding='utf-8', $root='think') {
    $xml    = &#39;<?xml version="1.0" encoding="&#39; . $encoding . &#39;"?>&#39;;
    $xml   .= &#39;<&#39; . $root . &#39;>&#39;;
    $xml   .= data_to_xml($data);
    $xml   .= &#39;</&#39; . $root . &#39;>&#39;;
    return $xml;
}
/**
 * 数据XML编码
 * @param mixed $data 数据
 * @return string
 */
function data_to_xml($data) {
    $xml = &#39;&#39;;
    foreach ($data as $key => $val) {
        is_numeric($key) && $key = "item id=\"$key\"";
        $xml    .=  "<$key>";
        $xml    .=  ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
        list($key, ) = explode(&#39; &#39;, $key);
        $xml    .=  "</$key>";
    }
    return $xml;
}

Recommended learning : "PHP Video Tutorial"

The above is the detailed content of How to convert array to xml in php. For more information, please follow other related articles on 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