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:
'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] ($ re Else se );} // ++ ++ // common formatting method // ++ ++/ * ** 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 ;}
For more articles about PHP's automatic identification of Restful API return content types, refer to PHP's Chinese website!