As the title, how does PHP automatically recognize the content of Third-party restful APIs, automatically rendering into JSON, XML, HTML, serialize, CSV, PHP, and other data?
This is not difficult, because the rest API is also based on HTTP protocol, as long as we follow the protocol, we can automate the identification of the content of the API, the following methods:
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 side (client) received the above header information, and then, when appropriate, automated processing, the reference code is as follows:
<?php//Request initialization $url = ' http://www.jb51.net ';
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_connecttimeout, 30);
The HTTP body content returned $response = curl_exec ($ch);
The contents of the Content-type of the HTTP header returned $contentType = Curl_getinfo ($ch, ' content_type ');
Closes the request resource curl_close ($ch); Results 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.serial
Ized ' => ' serialize ');
if (Strpos ($contentType, '; '))
{List ($contentType) = explode ('; ', $contentType);}
$contentType = Trim ($contentType);
if (Array_key_exists ($contentType, $autoDetectFormats)) {echo ' _ '. $autoDetectFormats [$contentType] ($response);} +++++++++++++++++++++++++++++++++++++++++++++++++++++++//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 the start and end of the "$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);
/** * Deserialize 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;
}