This article mainly introduces how PHP can automatically identify the types of returned content of RestfulAPI, and automatically render the content into json, xml, html, serialize, csv, php, and other data formats for output, for more information, see the following question: how does PHP automatically recognize the content of a third-party Restful API and render it into json, xml, html, serialize, csv, php, and other data?
In fact, this is not difficult, because the Rest API is based on the http protocol, as long as we follow the protocol, we can automatically identify the API content, the method is as follows:
1. the API server must return clear http Content-Type header information, for example:
Content-Type: application/json; charset=utf-8Content-Type: application/xml; charset=utf-8Content-Type: text/html; charset=utf-8
2. after receiving the above header information, the PHP client automatically processes it as needed. the reference code is as follows:
<? Php // request initialization $ url =' http://www.bitsCN.com '; $ Ch = curl_init (); curl_setopt ($ ch, CURLOPT_URL, $ url); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, 30 ); // returned http body Content $ response = curl_exec ($ ch); // returned http header Content-Type Content $ contentType = curl_getinfo ($ ch, 'content _ type'); // closes the Request resource curl_close ($ ch); // The result is output in an automatic format $ autoDetectFormats = array ('application/XML' => 'xml ', 'text/XML' => 'xml', 'applicatio N/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 );} // ++ ++ ++ ++/*** Format xml output */function _ xml ($ string) {return $ string? (Array) simplexml_load_string ($ string, 'simplexmlelement', LIBXML_NOCDATA): array () ;}/ *** format csv output */function _ csv ($ string) {$ data = array (); $ rows = explode ("\ n", trim ($ string); $ headings = explode (',', array_shift ($ rows); foreach ($ rows as $ row) {// use substr to remove "$ data_fields = explode ('","', trim (substr ($ row, 1,-1); if (count ($ data_fields) = count ($ headings )) {$ data [] = array_combine ($ headings, $ data_fields) ;}return $ data ;}/ *** format json output */function _ json ($ string) {return json_decode (trim ($ string), true);}/*** deserialization output */function _ serialize ($ string) {return unserialize (trim ($ string);}/*** execute PHP script output */function _ php ($ string) {$ string = trim ($ string ); $ populated = array (); eval ("\ $ populated = \" $ string \ ";"); return $ populated ;}