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

How to convert php array into xml format

藏色散人
藏色散人Original
2020-07-18 10:41:032309browse

How to convert php array to xml: first create a PHP sample file; then define an "array_Xml" method; then implement the conversion logic through foreach loop traversal and "is_array" and other functions; finally execute the file .

How to convert php array into xml format

PHP implements the method of converting an array into xml, as follows:

<?php
$elementLevel = 0 ;
function array_Xml($array, $keys = &#39;&#39;)
{
global $elementLevel;
if(!is_array($array))
{
  if($keys == &#39;&#39;){
  return $array;
  }else{
  return "\n<$keys>" . $array . "</$keys>\n";
  }
}else{
  foreach ($array as $key => $value)
  {
  $haveTag = true;
  if (is_numeric($key))
  {
   $key = $keys;
   $haveTag = false;
  }
  if($elementLevel == 0 )
  {
   $startElement = "<$key>";
   $endElement = "</$key>";
  }
  $text .= $startElement;
  if(!$haveTag)
  {
   $elementLevel++;
   $text .= "<$key>" . array_Xml($value, $key). "</$key>\n";
  }else{
   $elementLevel++;
   $text .= array_Xml($value, $key);
  }
  $text .= $endElement;
  }
}
return $text;
}
$array = array(
"employees" => array(
"employee" => array(
array(
"name" => "name one",
"position" => "position one"
),
array(
"name" => "name two",
"position" => "position two"
),
array(
"name" => "name three",
"position" => "position three"
)
)
)
);
echo array_Xml($array);
?>

Recommended: " PHP tutorial

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