如題,PHP如何自動識別第三方Restful API的內容,自動渲染成 json、xml、html、serialize、csv、php等數據?
其實這也不難,因為Rest API也是基於http協議的,只要我們按照協議走,就能做到自動化識別 API 的內容,方法如下:
1、API服務端要返回明確的 http Content-Type頭信息,如:
Content-Type: application/json; charset=utf-8 Content-Type: application/xml; charset=utf-8 Content-Type: text/html; charset=utf-8
2、PHP端(客戶端)接收到上述頭信息後,再酌情自動化處理,參考代碼如下:
<?php // 請求初始化 $url = 'http://www.bkjia.com'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // 返回的 http body 內容 $response = curl_exec($ch); // 返回的 http header 的 Content-Type 的內容 $contentType = curl_getinfo($ch, 'content_type'); // 關閉請求資源 curl_close($ch); // 結果自動格式輸出 $autoDetectFormats = array( 'application/xml' => 'xml', 'text/xml' => 'xml', 'application/json' => 'json', 'text/json' => 'json', 'text/csv' => 'csv', 'application/csv' => 'csv', 'application/vnd.php.serialized' => 'serialize' ); if (strpos($contentType, ';')) { list($contentType) = explode(';', $contentType); } $contentType = trim($contentType); if (array_key_exists($contentType, $autoDetectFormats)) { echo '_' . $autoDetectFormats[$contentType]($response); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++ // 常用 格式化 方法 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++ /** * 格式化xml輸出 */ function _xml($string) { return $string ? (array)simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA) : array(); } /** * 格式化csv輸出 */ function _csv($string) { $data = array(); $rows = explode("\n", trim($string)); $headings = explode(',', array_shift($rows)); foreach( $rows as $row ) { // 利用 substr 去掉 開始 與 結尾 的 " $data_fields = explode('","', trim(substr($row, 1, -1))); if (count($data_fields) === count($headings)) { $data[] = array_combine($headings, $data_fields); } } return $data; } /** * 格式化json輸出 */ function _json($string) { return json_decode(trim($string), true); } /** * 反序列化輸出 */ function _serialize($string) { return unserialize(trim($string)); } /** * 執行PHP腳本輸出 */ function _php($string) { $string = trim($string); $populated = array(); eval("\$populated = \"$string\";"); return $populated; }