PHP實(shí)現(xiàn)返回JSON和XML的類分享
更新時(shí)間:2015年01月28日 15:54:08 投稿:hebedich
這篇文章主要給大家分享了一個(gè)使用PHP實(shí)現(xiàn)返回JSON和XML的類,非常實(shí)用,希望大家能夠喜歡
代碼很簡(jiǎn)潔,功能也很簡(jiǎn)單實(shí)用,這里就不多廢話了,直接奉上代碼:
復(fù)制代碼 代碼如下:
<?php
class Reponse{
//private $result = array('code'=null,'message'=null,'data'=>null);
/**
* @desc 返回JSON格式
* @param int $code
* @param string $message
* @param array $data
* return string
*/
public static function json($code,$message = null,$data = array()){
if(!is_numeric($code)){
return false;
}
$result = array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
return json_encode($result);
exit;
}
/**
* @desc 返回xml格式數(shù)據(jù)
* @parma int $code 狀態(tài)碼
* @param string $message 提示
* @param array $data 數(shù)據(jù)
* return string
*/
public static function xml($code,$message = '',$data = array()){
if(!is_numeric($code)){
return false;
}
$result = array(
'code'=>$code,
'message'=>$message,
'data'=>$data
);
$xml = '';
$xml .= "<?xml version='1.0' encoding='UTF-8'?>\n";
$xml .= "<root>\n";
$xml .= self::xmlEncode($result);
$xml .= "</root>";
header("Content-Type:text/xml");
echo $xml;
}
public static function xmlEncode($result){
$xml = $attr ='';
foreach($result as $key=>$val){
if(is_numeric($key)){
$attr = "id='{$key}'";
$key = "item{$key}";
}
$xml .= "<{$key} {$attr}>";
$xml .= is_array($val) ? self::xmlEncode($val) : $val;
$xml .= "</{$key}>\n";
}
return $xml;
}
}
$data = array(
'id'=>1,
'age'=>20,
'username'=>'tim',
'others'=>array(1,2,3),
);
Reponse::xml(200,'success',$data);
Reponse::json(200,'success',$data);
小伙伴們可以直接拿去使用,使用方法在代碼的最下方:)
您可能感興趣的文章:
- php+Ajax處理xml與json格式數(shù)據(jù)的方法示例
- PHP以json或xml格式返回請(qǐng)求數(shù)據(jù)的方法
- php實(shí)現(xiàn)xml與json之間的相互轉(zhuǎn)換功能實(shí)例
- PHP生成json和xml類型接口數(shù)據(jù)格式
- php json與xml序列化/反序列化
- php 備份數(shù)據(jù)庫代碼(生成word,excel,json,xml,sql)
- PHP封裝的XML簡(jiǎn)單操作類完整實(shí)例
- PHP數(shù)組生成XML格式數(shù)據(jù)的封裝類實(shí)例
- php封裝json通信接口詳解及實(shí)例
- PHP封裝返回Ajax字符串和JSON數(shù)組的方法
- PHP封裝XML和JSON格式數(shù)據(jù)接口操作示例
相關(guān)文章
如何在Ubuntu下啟動(dòng)Apache的Rewrite功能
本篇文章是對(duì)在Ubuntu下啟動(dòng)Apache的Rewrite功能的具體操作步驟進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-07-07
php生成動(dòng)態(tài)驗(yàn)證碼gif圖片
這篇文章主要介紹了php生成動(dòng)態(tài)驗(yàn)證碼gif圖片的相關(guān)資料,需要的朋友可以參考下2015-10-10
php中實(shí)現(xiàn)獲取隨機(jī)數(shù)組列表的自定義函數(shù)
這篇文章主要介紹了php中實(shí)現(xiàn)獲取隨機(jī)數(shù)組列表的自定義函數(shù),本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-04-04
PHP實(shí)現(xiàn)的各類hash算法長(zhǎng)度及性能測(cè)試實(shí)例
這篇文章主要介紹了PHP實(shí)現(xiàn)的各類hash算法長(zhǎng)度及性能測(cè)試,結(jié)合具體實(shí)例形式分析了php hash計(jì)算的相關(guān)操作技巧,需要的朋友可以參考下2017-08-08

