Home > php教程 > php手册 > PHP如何实现数组array转换成xml(附代码)

PHP如何实现数组array转换成xml(附代码)

PHPz
Release: 2018-10-20 16:26:00
Original
911 people have browsed it

这篇文章主要介绍了PHP实现数组array转换成xml的方法,涉及php针对数组的遍历及xml格式文件的构造技巧,具有一定参考借鉴价值,需要的朋友可以参考下

<?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

【相关教程推荐】

1. php编程从入门到精通全套视频教程
2. php从入门到精通 
3. bootstrap教程

Related labels:
source:php.cn
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template