標籤:風格 sel array elf response accept 返回結果 echo version
接前一篇PHP實現RESTful風格的API執行個體(一)
Response.php :包含一個Request類,即輸出類。根據接收到的Content-Type,將Request類返回的數組拼接成對應的格式,加上header後輸出
<?php/** * 輸出類 */class Response{ const HTTP_VERSION = "HTTP/1.1"; //返回結果 public static function sendResponse($data) { //擷取資料 if ($data) { $code = 200; $message = ‘OK‘; } else { $code = 404; $data = array(‘error‘ => ‘Not Found‘); $message = ‘Not Found‘; } //輸出結果 header(self::HTTP_VERSION . " " . $code . " " . $message); $content_type = isset($_SERVER[‘CONTENT_TYPE‘]) ? $_SERVER[‘CONTENT_TYPE‘] : $_SERVER[‘HTTP_ACCEPT‘]; if (strpos($content_type, ‘application/json‘) !== false) { header("Content-Type: application/json"); echo self::encodeJson($data); } else if (strpos($content_type, ‘application/xml‘) !== false) { header("Content-Type: application/xml"); echo self::encodeXml($data); } else { header("Content-Type: text/html"); echo self::encodeHtml($data); } } //json格式 private static function encodeJson($responseData) { return json_encode($responseData); } //xml格式 private static function encodeXml($responseData) { $xml = new SimpleXMLElement(‘<?xml version="1.0"?><rest></rest>‘); foreach ($responseData as $key => $value) { if (is_array($value)) { foreach ($value as $k => $v) { $xml->addChild($k, $v); } } else { $xml->addChild($key, $value); } } return $xml->asXML(); } //html格式 private static function encodeHtml($responseData) { $html = "<table border=‘1‘>"; foreach ($responseData as $key => $value) { $html .= "<tr>"; if (is_array($value)) { foreach ($value as $k => $v) { $html .= "<td>" . $k . "</td><td>" . $v . "</td>"; } } else { $html .= "<td>" . $key . "</td><td>" . $value . "</td>"; } $html .= "</tr>"; } $html .= "</table>"; return $html; }}
index.php :入口檔案,調用Request類取得資料後交給Response處理,最後返回結果
<?php//資料操作類require(‘Request.php‘);//輸出類require(‘Response.php‘);//擷取資料$data = Request::getRequest();//輸出結果Response::sendResponse($data);
下一篇PHP實現RESTful風格的API執行個體(三)
PHP實現RESTful風格的API執行個體(二)