PHP-数组生成xml数据, 最近因为公司和第三方合作, 经常要实现第三方接口,以xml数据作为交换格式, 写了个小demo,数组生成xml内容
<?php
class Response{
public static function getXml($data=array()){
header("Content-Type:text/xml"); // 告诉浏览器这是xml数据
$xml = '<?xml version="1.0" encoding="UTF-8" ?>'; //告诉浏览器和解析器这是1.0版本,编码格式是utf-8
$xml .= "\n<root>"; 换行符,看的更直观
$xml .= self::arrayToXml($data);
$xml .= '</root>';
return $xml;
}
public static function arrayToXml($data){
$attr = '';
$xml = '';
if(is_array($data)){
foreach($data as $key => $val){
if(is_numeric($key)){
$attr = "id='$key'";
$key = "item ";
}
$xml .= "\n<{$key}{$attr}>";
$xml .= is_array($val) ? self::arrayToXml($val) : $val;
$xml .= "</{$key}>";
}
}
$xml.="\n";
return $xml;
}
}
$data = array(
'orders' => array(
'order' =>array(
'out_no' => 1234,
'order_status' => 1,
'shipping_status' => 0,
'pay_status' => 0,
'consignee' => 'xxx',
'address' => '最晚17:00前送到丰台区汽车博物馆东路盈坤世纪大厦G座503',
'goods' => array(
'good' => array(
'goods_sn' => '123',
'goods_number' => 100,
'goods_price' => 138.88,
'goods_discount' => 3,
'is_peijian' => 0
),
'numbers' => array('one','two','tree'),
)
)
)
);
Response::getXml($data);