Title, how does PHP automatically identify third-party RESTful API content and automatically render it into JSON, XML, HTML, serialize, CSV, PHP and other data?
In fact, this is not difficult, because the rest API is also based on the HTTP protocol, as long as we follow the protocol, we can do the automation to identify the content of the API, the method is as follows:
1, the API server to return the explicit HTTP Content-type header information, such as
Content-type:application/json; Charset=utf-8
Content-type:application/xml; Charset=utf-8
content-type:text/html; Charset=utf-8
2, the PHP terminal (client) received the above header information, and then, as appropriate, automated processing, the reference code is as follows:
<?php//request initialization of the ' 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);//return HTTP body content $response = Curl_exec ($ch);//Returns the contents of the HTTP header content-type $contenttype = Curl_getinfo ($ch, ' content_type ');//Close Request Resource Curl_close ($ch);//result automatic format output $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);} +++++++++++++++++++++++++++++++++++++++++++++++++++++++//Common formatting methods//++++++++++++++++++++++++++++++++++++++++++ +++++++++++++/** * Formatted 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 (', ', Arra Y_shift ($rows)); foreach ($rows as $row) {//Use substr to remove start and end "$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;}
How PHP automatically recognizes the content of third-party restful APIs and automatically renders data in JSON, XML, HTML, serialize, CSV, PHP, and more