如题,PHP如何自动识别第三方Restful API的内容,自动渲染成 json、xml、html、serialize、csv、php等数据?
其实这也不难,因为Rest API也是基于http协议的,只要我们按照协议走,就能做到自动化识别 API 的内容,方法如下:
1、API服务端要返回明确的 http Content-Type头信息,如
Content-Type: application/json; charset=utf-8
Content-Type: application/xml; charset=utf-8
Content-Type: text/html; charset=utf-8
2、PHP端(客户端)接收到上述头信息后,再酌情自动化处理,参考代码如下:
view source?
001
002
// 请求初始化
003
$url = 'http://blog.snsgou.com/user/123456';
004
$ch = curl_init();
005
curl_setopt($ch, CURLOPT_URL, $url);
006
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
007
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
008
009
// 返回的 http body 内容
010
$response = curl_exec($ch);
011
012
// 返回的 http header 的 Content-Type 的内容
013
$contentType = curl_getinfo($ch, 'content_type');
014
015
// 关闭请求资源
016
curl_close($ch);
017
018
// 结果自动格式输出
019
$autoDetectFormats = array(
020
'application/xml' => 'xml',
021
'text/xml' => 'xml',
022
'application/json' => 'json',
023
'text/json' => 'json',
024
'text/csv' => 'csv',
025
'application/csv' => 'csv',
026
'application/vnd.php.serialized' => 'serialize'
027
);
028
029
if (strpos($contentType, ';'))
030
{
031
list($contentType) = explode(';', $contentType);
032
}
033
034
$contentType = trim($contentType);
035
036
if (array_key_exists($contentType, $autoDetectFormats))
037
{
038
echo '_' . $autoDetectFormats[$contentType]($response);
039
}
040
041
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
042
// 常用 格式化 方法
043
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
044
045
/**
046
* 格式化xml输出
047
*/
048
function _xml($string)
049
{
050
return $string ? (array)simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA) : array();
051
}
052
053
/**
054
* 格式化csv输出
055
*/
056
function _csv($string)
057
{
058
$data = array();
059
060
$rows = explode("\n", trim($string));
061
$headings = explode(',', array_shift($rows));
062
foreach( $rows as $row )
063
{
064
// 利用 substr 去掉 开始 与 结尾 的 "
065
$data_fields = explode('","', trim(substr($row, 1, -1)));
066
if (count($data_fields) === count($headings))
067
{
068
$data[] = array_combine($headings, $data_fields);
069
}
070
}
071
072
return $data;
073
}
074
075
/**
076
* 格式化json输出
077
*/
078
function _json($string)
079
{
080
return json_decode(trim($string), true);
081
}
082
083
/**
084
* 反序列化输出
085
*/
086
function _serialize($string)
087
{
088
return unserialize(trim($string));
089
}
090
091
/**
092
* 执行PHP脚本输出
093
*/
094
function _php($string)
095
{
096
$string = trim($string);
097
$populated = array();
098
eval("\$populated = \"$string\";");
099
100
return $populated;
101
}