PHP如何自動識別第三方Restful API的內容,自動渲染成 json、xml、html、serialize、csv、php等資料

來源:互聯網
上載者:User

標籤:

如題,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://blog.snsgou.com/user/123456‘;$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;}

PHP如何自動識別第三方Restful API的內容,自動渲染成 json、xml、html、serialize、csv、php等資料

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.