如題,PHP如何自動識別第三方Restful API的內容,自動渲染成 json、xml、html、serialize、csv、php等數據?
其實這也不難,因為Rest API也是基于http協議的,只要我們按照協議走,就能做到自動化識別 API 的內容,方法如下:
1、API服務端要返回明確的 http Content-Type頭信息,如:
1
2
3
|
Content-Type: application/json; charset=utf-8 Content-Type: application/xml; charset=utf-8 Content-Type: text/html; charset=utf-8 |
2、PHP端(客戶端)接收到上述頭信息后,再酌情自動化處理,參考代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
<?php // 請求初始化 $url = 'http://www.zmynmublwnt.cn' ; $ch = curl_init(); curl_setopt( $ch , CURLOPT_URL, $url ); curl_setopt( $ch , CURLOPT_RETURNTRANSFER, 1); curl_setopt( $ch , CURLOPT_CONNECTTIMEOUT, 30); // 返回的 http body 內容 $response = curl_exec( $ch ); // 返回的 http header 的 Content-Type 的內容 $contentType = curl_getinfo( $ch , 'content_type' ); // 關閉請求資源 curl_close( $ch ); // 結果自動格式輸出 $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 去掉 開始 與 結尾 的 " $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 )); } /** * 執行PHP腳本輸出 */ function _php( $string ) { $string = trim( $string ); $populated = array (); eval ( "\$populated = \"$string\";" ); return $populated ; } |