php生成XML数据
1)组装字符串
2)使用系统类
- DomDocument
- XMLWriter
- SimpleXML
这里以第一种方法举例:
<?php
class Response
{
/**按json方式输出通信数据
* @param integer $code 状态码
* @param string $message 提示信息
* @param array $data 数据
* return string
*/
public static function json($code, $message = '', $data = array())
{
if(!is_numeric($code)){
return '';
}
$result = array(
'code' => $code,
'message' => $message,
'date' => $data
);
echo json_encode($result);
exit;
}
public static function xml(){
header("content-type:text/xml");
$xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
$xml .= "<root>\n";
$xml .="<code>200</code>\n";
$xml .="<message>数据返回成功</message>\n";
$xml .="<data>\n";
$xml .="<id>1</id>\n";
$xml .="<name>ceshi</name>\n";
$xml .="</data>\n";
$xml .= "</root>\n";
echo $xml;
}
public static 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>\n";
$xml .= self::xmlToEncode($result);
echo $xml .="</root>";
}
public static function xmlToEncode($data){
$xml = $attr = '';
foreach($data as $key => $value){
if(is_numeric($key)){
$attr = " id='{$key}'";
$key = 'item';
}
$xml .= "<{$key}{$attr}>";
$xml .= is_array($value)?self::xmlToEncode($value):$value; //递归,如果value是数组,递归输出节点。
$xml .= "</{$key}>\n";
}
return $xml;
}
}
$arr = array(
'id' => 1,
'name' => 'xxx',
'type' => array(4,5,6),
'test' => array(1,25,345=>array(123,'zifuchuan'))
);
//<0>4</0> <item id='0'>4</item>
//Response::json(200,'数据返回成功',$arr);
//Response::xml();
Response::xmlEncode(200,'success',$arr);