Home  >  Article  >  Backend Development  >  How to convert php array to xml

How to convert php array to xml

藏色散人
藏色散人Original
2020-08-25 10:38:272784browse

php array to xml method: first create a PHP sample file; then use the "data_to_xml" method to convert the array data to xml; finally return the conversion result through return.

How to convert php array to xml

Recommended: "PHP Video Tutorial"

php converts arrays to xml format

php converts the array into xml format, taken 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    = '';
    $xml   .= '<' . $root . '>';
    $xml   .= data_to_xml($data);
    $xml   .= '';
    return $xml;
}
/**
 * 数据XML编码
 * @param mixed $data 数据
 * @return string
 */
function data_to_xml($data) {
    $xml = '';
    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(' ', $key);
        $xml    .=  "";
    }
    return $xml;
}

The above is the detailed content of How to convert php array to xml. 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