Home > Backend Development > PHP Tutorial > PHP method to convert array into xml

PHP method to convert array into xml

高洛峰
Release: 2023-03-03 22:50:02
Original
1435 people have browsed it

The example in this article describes the method of converting array into xml in PHP. Share it with everyone for your reference, the details are 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);
?>
Copy after login

I hope this article will be helpful to everyone in PHP programming.


For more articles related to PHP's methods of converting arrays into xml, please pay attention to the PHP Chinese website!


Related labels:
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template