php教程

超轻量级php框架startmvc

PHP实现数组array转换成xml的方法

更新时间:2020-03-11 00:01:54 作者:startmvc
本文实例讲述了PHP实现数组array转换成xml的方法。分享给大家供大家参考,具体如下:<

本文实例讲述了PHP实现数组array转换成xml的方法。分享给大家供大家参考,具体如下:


<?php
$elementLevel = 0 ;
function array_Xml($array, $keys = '')
{
global $elementLevel;
if(!is_array($array))
{
 if($keys == ''){
 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);
?>

PHP 数组 array 转换 xml