我有一个可与mailchimp API配合使用的curl请求,但我想尝试使用Guzzle。我无法获得使用Guzzle的请求。
我想要的是将API响应转换为我可以操纵的php数组。
我已经尝试了以下代码将curl转换为gglele,但无法正常工作。
此代码可以正常工作
function apiRequest($url,$post = NULL) {
global $api_key;
$httpHeader = array(
'Accept: application/vnd.api+json',
'Content-Type: application/vnd.api+json',
'Authorization: apikey ' . $api_key
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(isset($post)) curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$responseContent = curl_exec($ch);
$response['headers'] = curl_getinfo($ch);
curl_close($ch);
return json_decode($responseContent,true);
}
当我尝试这个耗时的代码时,我没有看到请求的结果,但也没有收到错误。
$client = new GuzzleHttp\Client();
$json = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'apikey ' . $api_key,
'Accept' => 'application/json',
'Content-type' => 'application/json'
]]);
预期结果是一个数组,我可以使用以下数据进行处理:
Array
(
[id] => 14721
[name] => 2019_3_test
[member_count] => 1
[type] => static
[created_at] => 2019-03-23T00:55:02+00:00
[updated_at] => 2019-03-23T00:55:02+00:00
[list_id] => f4f3d03d5f
)
实际结果是这样
GuzzleHttp\Psr7\Response Object ( [reasonPhrase:GuzzleHttp\Psr7\Response:private] => OK [statusCode:GuzzleHttp\Psr7\Response:private] => 200 [headers:GuzzleHttp\Psr7\Response:private] => Array ( [Server] => Array ( [0] => openresty ) [Content-Type] => Array ( [0] => application/json; charset=utf-8 ) [Content-Length] => Array ( [0] => 1326 ) [Vary] => Array ( [0] => Accept-Encoding ) [X-Request-Id] => Array ( [0] => 342c0c4b-5629-4bc4-aa7d-4a7f6d51af7b ) [Link] => Array ( [0] => ; rel="describedBy" ) [Date] => Array ( [0] => Sat, 23 Mar 2019 04:43:57 GMT ) [Connection] => Array ( [0] => keep-alive ) [Set-Cookie] => Array ( [0] => _AVESTA_ENVIRONMENT=prod; path=/ [1] => _mcid=1.746c6e8ecb1ba60edb191ed80a3c86c1; expires=Sun, 22-Mar-2020 04:43:57 GMT; Max-Age=31536000; path=/; domain=.mailchimp.com ) ) [headerNames:GuzzleHttp\Psr7\Response:private] => Array ( [server] => Server [content-type] => Content-Type [content-length] => Content-Length [vary] => Vary [x-request-id] => X-Request-Id [link] => Link [date] => Date [connection] => Connection [set-cookie] => Set-Cookie ) [protocol:GuzzleHttp\Psr7\Response:private] => 1.1 [stream:GuzzleHttp\Psr7\Response:private] => GuzzleHttp\Psr7\Stream Object ( [stream:GuzzleHttp\Psr7\Stream:private] => Resource id #40 [size:GuzzleHttp\Psr7\Stream:private] => [seekable:GuzzleHttp\Psr7\Stream:private] => 1 [readable:GuzzleHttp\Psr7\Stream:private] => 1 [writable:GuzzleHttp\Psr7\Stream:private] => 1 [uri:GuzzleHttp\Psr7\Stream:private] => php://temp [customMetadata:GuzzleHttp\Psr7\Stream:private] => Array ( ) ) )
答案 0 :(得分:1)
使用食口,您的$client->request
返回一个Response
对象。要获取输出为数组,请解码true为第二个参数的json字符串。
$response = $client->request('GET', $url, [ ... ]]);
$json_array = json_decode($response->getBody(), true);