您的位置:首页 > 编程语言 > PHP开发

PHP-source-xmlEncode-1

2015-07-25 23:29 731 查看
功能:将数组转换成xml文档格式返回。

实现:通过遍历数组,拼接xml文本。使用header头声明为返回xml格式

适用:接口的场合

代码一

function xml_encode2($data){
$xmlstr = '';
foreach($data as $key => $value){
$attr = "";
if(is_numeric($key)){
$attr = " id='$key'";
$key = "item";
}
$xmlstr .= "<{$key}{$attr}>";
if(is_array($value)){
$xmlstr .= xml_encode2($value);
}
else{
$xmlstr .= $value;
}
$xmlstr .="</$key>";
}
return $xmlstr;
}


代码二

function xml_encode($root,$data){
$xmlstr = "<$root>";
foreach($data as $key => $value){
if(is_numeric($key)){
$xmlstr .= "<item id=\"$key\">";
if(is_array($value)){
$xmlstr .= xml_encode('item', $value);
}
else{
$xmlstr .= "$value";
}
$xmlstr .= '</item>';
}else{
if(is_array($value)){
$xmlstr .= xml_encode($key, $value);
}
else{
$xmlstr .= "<$key>{$value}</$key>";
}
}
}
$xmlstr .= "</$root>";
return $xmlstr;
}


因为xml标签不能出现数字,所以代码中对键是数字的元素处理方式:

<item id="$key">$value</item>


请简单修改代码使用:

以下是验证代码一使用的部分:

header('Content-Type:text/xml');
$xmlheader = "<?xml version='1.0' encoding='UTF-8' ?><root>";
echo $xmlheader.xml_encode2($array).'</root>';
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  is-numeric xml php