Maison  >  Article  >  développement back-end  >  Convertir des tableaux en fichiers XML et vice versa

Convertir des tableaux en fichiers XML et vice versa

php中世界最好的语言
php中世界最好的语言original
2018-03-24 10:10:141222parcourir

Cette fois, je vais vous présenter la conversion mutuelle des tableaux et des fichiers XML. Quelles sont les précautions pour la conversion de tableaux et de fichiers XML. Jetons un coup d'œil.

Récemment, j'ai effectué le paiement WeChat, et le serveur WeChat renvoie tous les fichiers XML, il doit donc être converti en tableau pour une utilisation facile. Sans plus tarder, passons directement au code :

.

1. Convertir XML en tableau

/**
 * 将xml转为array
 * @param string  $xml xml字符串或者xml文件名
 * @param bool   $isfile 传入的是否是xml文件名
 * @return array  转换得到的数组
 */
function xmlToArray($xml,$isfile=false){
  //禁止引用外部xml实体
  libxml_disable_entity_loader(true);
  if($isfile){
    if(!file_exists($xml)) return false;
    $xmlstr = file_get_contents($xml);
  }else{
    $xmlstr = $xml;
  }
  $result= json_decode(json_encode(simplexml_load_string($xmlstr, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
  return $result;
}

Exemple d'utilisation :

$xmlDoc=<<<ETO
<books>
 <book>
 <author>Jack Herrington</author>
 <title>PHP Hacks</title>
 <publisher>O'Reilly</publisher>
 </book>
 <book>
 <author>Jack Herrington</author>
 <title>Podcasting Hacks</title>
 <publisher>O'Reilly</publisher>
 </book>
 <book>
 <author>XML格式化</author>
 <title>脚本之家在线工具</title>
 <publisher>tools.jb51.net</publisher>
 </book>
</books>
ETO;
$relarr=xmlToArray($xmlDoc);
print_r($relarr);

Résultat d'exécution :

Array
(
  [book] => Array
    (
      [0] => Array
        (
          [author] => Jack Herrington
          [title] => PHP Hacks
          [publisher] => O'Reilly
        )
      [1] => Array
        (
          [author] => Jack Herrington
          [title] => Podcasting Hacks
          [publisher] => O'Reilly
        )
      [2] => Array
        (
          [author] => XML格式化
          [title] => 脚本之家在线工具
          [publisher] => tools.jb51.net
        )
    )
)

2. Convertir un tableau en XML

/**
 * 数组转xml字符
 * @param string  $xml xml字符串
**/
function arrayToXml($data){
  if(!is_array($data) || count($data) <= 0){
    return false;
  }
  $xml = "<xml>";
  foreach ($data as $key=>$val){
    if (is_numeric($val)){
      $xml.="<".$key.">".$val."</".$key.">";
    }else{
      $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    }
  }
  $xml.="</xml>";
  return $xml;
}

Exemple d'utilisation :

$arrDoc= array("author"=>"XML格式化","title"=>"脚本之家在线工具","publisher"=>"tools.jb51.net");
$xmlrel=arrayToXml($arrDoc);
//运行结果:<xml><author><![CDATA[XML格式化]]></author><title><![CDATA[脚本之家在线工具]]></title><publisher><![CDATA[tools.jb51.net]]></publisher></xml>

Je crois que vous maîtrisez la méthode après avoir lu le cas dans cet article, il y a des choses plus excitantes. Veuillez prêter attention aux autres articles connexes sur le site Web chinois de php !

Lecture recommandée :

Vue créant un carrousel d'images

JS obtient le premier élément dans la liste déroulante de sélection. valeur de

Comment gérer l'échec de l'installation d'Electron

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