依據 HTTP Content-Type 標頭自動判斷 API 回應格式,並呼叫對應解析函數輸出 PHP 陣列,支援 JSON、XML、CSV、PHP 序列化、純文字等格式。
content_typecharset 等參數,取得純 MIME 型別$url = 'https://www.jb51.net';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$response = curl_exec($ch);
$contentType = curl_getinfo($ch, 'content_type');
curl_close($ch);
if (strpos($contentType, ';')) {
list($contentType) = explode(';', $contentType);
}
$contentType = trim($contentType);
$autoDetectFormats = [
'application/xml' => 'xml',
'text/xml' => 'xml',
'application/json' => 'json',
'text/json' => 'json',
'text/csv' => 'csv',
'application/csv' => 'csv',
'application/vnd.php.serialized' => 'serialize',
];
if (array_key_exists($contentType, $autoDetectFormats)) {
echo '_' . $autoDetectFormats[$contentType]($response);
}
function _xml($string) {
return $string ? (array)simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA) : [];
}
function _csv($string) {
$data = []; $rows = explode("\n", trim($string));
$headings = explode(',', array_shift($rows));
foreach ($rows as $row) {
$fields = explode('","', trim(substr($row, 1, -1)));
if (count($fields) === count($headings)) $data[] = array_combine($headings, $fields);
}
return $data;
}
function _json($string) { return json_decode(trim($string), true); }
function _serialize($string) { return unserialize(trim($string)); }
function _php($string) { $populated = []; eval("\$populated = \"$string\";"); return $populated; }
application/x-msgpack、application/x-protobuf 等現代格式ApiResponseParser 類別