您好,登錄后才能下訂單哦!
怎么在PHP中生成一個(gè)json和xml類型的接口?相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
php生成接口通信數(shù)據(jù)
/** * 生成接口數(shù)據(jù)格式 */ class Response{ /** * [show 按綜合方式輸出數(shù)據(jù)] * @param [int] $code [狀態(tài)碼] * @param [string] $message [提示信息] * @param array $data [數(shù)據(jù)] * @param [string] $type [類型] * @return [string] [返回值] */ public static function show($code, $message, $data = array(),$type = ''){ if(!is_numeric($code)){ return ''; } $result = array( 'code' => $code, 'message' => $message, 'data' => $data ); if($type == 'json'){ return self::json($code, $message, $data); }elseif($type == 'xml'){ return self::xml($code, $message, $data); }else{ //TODO } } /** * [json 按json方式輸出數(shù)據(jù)] * @param [int] $code [狀態(tài)碼] * @param [string] $message [提示信息] * @param [array] $data [數(shù)據(jù)] * @return [string] [返回值] */ public static function json($code, $message, $data = array()){ if(!is_numeric($code)){ return ''; } $result = array( 'code' => $code, 'message' => $message, 'data' => $data ); $result = json_encode($result); return $result; } /** * [xml 按xml格式生成數(shù)據(jù)] * @param [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 ''; } $result = array( 'code' => $code, 'message' => $message, 'data' => $data ); header("Content-Type:text/xml"); $xml = "<?xml version='1.0' encoding='UTF-8'?>\n"; $xml .= "<root>\n"; $xml .= self::xmlToEncode($data); $xml .= "</root>"; return $xml; } public static function xmlToEncode($data){ $xml = ''; foreach($data as $key => $value){ if(is_numeric($key)){ $attr = "id='{$key}'"; $key = "item"; } $xml .= "<{$key} {$attr}>\n"; $xml .= is_array($value) ? self::xmlToEncode($value) : "{$value}\n"; $xml .= "</{$key}>\n"; } return $xml; } } //測(cè)試 $grade = array("score" => array(70, 95, 70.0, 60, "70"), "name" => array("Zhang San", "Li Si", "Wang Wu", "Zhao Liu", "TianQi")); $response = new Response(); $result = $response :: show(200,'success',$grade,'json'); print_r($result);
看完上述內(nèi)容,你們掌握怎么在PHP中生成一個(gè)json和xml類型的接口的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。