Maison  >  Article  >  développement back-end  >  Comment convertir un tableau en XML en php

Comment convertir un tableau en XML en php

藏色散人
藏色散人original
2021-07-14 10:17:363170parcourir

Comment convertir un tableau en XML en PHP : créez d'abord un exemple de fichier PHP ; puis utilisez la méthode "function data_to_xml($data) {...}" pour convertir le tableau au format XML.

Comment convertir un tableau en XML en php

L'environnement d'exploitation de cet article : système windows7, version PHP7.1, ordinateur DELL G3

Comment convertir un tableau en xml avec php ?

php convertit un tableau au format XML

php convertit un tableau au format XML, extrait de thinkphp, enregistrez-le

/**
 * 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;
}

Apprentissage recommandé : "Tutoriel vidéo PHP"

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn