《PHP編程:PHP實(shí)現(xiàn)自動(dòng)識(shí)別Restful API的返回內(nèi)容類型》要點(diǎn):
本文介紹了PHP編程:PHP實(shí)現(xiàn)自動(dòng)識(shí)別Restful API的返回內(nèi)容類型,希望對(duì)您有用。如果有疑問,可以聯(lián)系我們。
PHP實(shí)戰(zhàn)如題,PHP如何自動(dòng)識(shí)別第三方Restful API的內(nèi)容,自動(dòng)渲染成 json、xml、html、serialize、csv、php等數(shù)據(jù)?
PHP實(shí)戰(zhàn)其實(shí)這也不難,因?yàn)镽est API也是基于http協(xié)議的,只要我們按照協(xié)議走,就能做到自動(dòng)化識(shí)別 API 的內(nèi)容,方法如下:
PHP實(shí)戰(zhàn)1、API服務(wù)端要返回明確的 http Content-Type頭信息,如:
PHP實(shí)戰(zhàn)
Content-Type: application/json; charset=utf-8
Content-Type: application/xml; charset=utf-8
Content-Type: text/html; charset=utf-8
PHP實(shí)戰(zhàn)2、PHP端(客戶端)接收到上述頭信息后,再酌情自動(dòng)化處理,參考代碼如下:
PHP實(shí)戰(zhàn)
<?php
// 哀求初始化
$url = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
// 返回的 http body 內(nèi)容
$response = curl_exec($ch);
// 返回的 http header 的 Content-Type 的內(nèi)容
$contentType = curl_getinfo($ch, 'content_type');
// 關(guān)閉哀求資源
curl_close($ch);
// 結(jié)果自動(dòng)格式輸出
$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);
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
// 常用 格式化 方法
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
/**
* 格式化xml輸出
*/
function _xml($string)
{
return $string ? (array)simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA) : array();
}
/**
* 格式化csv輸出
*/
function _csv($string)
{
$data = array();
$rows = explode("\n", trim($string));
$headings = explode(',', array_shift($rows));
foreach( $rows as $row )
{
// 利用 substr 去掉 開始 與 結(jié)尾 的 "
$data_fields = explode('","', trim(substr($row, 1, -1)));
if (count($data_fields) === count($headings))
{
$data[] = array_combine($headings, $data_fields);
}
}
return $data;
}
/**
* 格式化json輸出
*/
function _json($string)
{
return json_decode(trim($string), true);
}
/**
* 反序列化輸出
*/
function _serialize($string)
{
return unserialize(trim($string));
}
/**
* 執(zhí)行PHP腳本輸出
*/
function _php($string)
{
$string = trim($string);
$populated = array();
eval("\$populated = \"$string\";");
return $populated;
}
《PHP編程:PHP實(shí)現(xiàn)自動(dòng)識(shí)別Restful API的返回內(nèi)容類型》是否對(duì)您有啟發(fā),歡迎查看更多與《PHP編程:PHP實(shí)現(xiàn)自動(dòng)識(shí)別Restful API的返回內(nèi)容類型》相關(guān)教程,學(xué)精學(xué)透。維易PHP學(xué)院為您提供精彩教程。
轉(zhuǎn)載請(qǐng)注明本頁(yè)網(wǎng)址:
http://www.fzlkiss.com/jiaocheng/12452.html