方法
(1)组装字符串生成xml格式的文档
栗子:
<?php
header("Content-Type:text/xml");
function xml()
{
$xml="<?xml version='1.0' encoding='UTF-8'?>";
$xml.="<root>";
$xml.="<code>200</code>";
$xml.="<code>数据返回成功</code>";
$xml.="<data>";
$xml.="<id>1</id>";
$xml.="<name>singwa</name>";
$xml.="</data>";
$xml.="</root>";
echo $xml;
}
开始封装
//code 状态码(200,400)等 message 提示信息(200 成功 400 失败) //data 返回数据
<?php
function xmlEncode($code,$message,$data=array())
{
if(is_numeric($code))
{
return '';
}
$result=array(
'code'=>$code,
'message'=>$message,
'data'=>$data,
);
header("Content-Type:text/xml");
$xml="<?xml version='1.0' encoding='UTF-8'?>";
$xml.="<root>";
$xml.=makecode($result);
$xml.="</root>";
return $xml;
}
//将数组转换为xml代码
function makecode($data)
{
foreach($data as $key=>$value)
{
$xml.="<{$key}>";
//如果value值仍然是个数组,继续使用这种方法。
$xml.=is_array($value)? makecode($value):$value;
$xml.="</{$key}>\n";
}
return $xml;
}
封装结束,现在编写测试代码
$data=array(
'id'=>1,
'name'=>'singwa',
'type'=>array('id'=>1,
'name'=>'singwa'),
);
$xml=xmlEncode(200,'success',$data);
显示结果:
<root>
<code>200</code>
<message>success</message>
<data>
<id>1</id>
<name>singwa</name>
<type>
<id>1</id>
<name>singwa</name>
</type>
</data>
</root>