Maison  >  Article  >  développement back-end  >  PHP implémente la conversion mutuelle entre les tableaux et les fichiers XML

PHP implémente la conversion mutuelle entre les tableaux et les fichiers XML

小云云
小云云original
2018-03-16 09:47:331355parcourir

Cet article vous présente principalement la fonction de conversion mutuelle des tableaux et des fichiers XML implémentée par PHP. Il analyse les compétences opérationnelles de PHP pour la conversion mutuelle des données et des tableaux au format XML sous forme d'exemples. J'espère que cela pourra aider tout le monde.

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><演示]></title
><publisher><![CDATA[tools.jb51.net]]></publisher></xml>

Recommandations associées :

php Exemple de code pour gérer la conversion entre tableaux et XML

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