PHP - 从curl_exec获取特定值

时间:2017-06-29 18:35:58

标签: php curl

我正在使用cURL进行一些API工作。我正在注销这样的会话响应:

$headers = array(
        'Authorization: Bearer '. $accessToken,
        'Content-Type: image/png',
        'Content-Disposition: attachment; filename="'. $filename .'"',
        'Content-Length: '. $fileSize
    );

$curlSession = curl_init($apiURL);
curl_setopt($attachmentSession, CURLOPT_HTTPHEADER, $headers);   
curl_setopt($attachmentSession, CURLOPT_HEADER, true);   
curl_setopt($attachmentSession, CURLOPT_INFILE, $fileStream);
curl_setopt($attachmentSession, CURLOPT_INFILESIZE, $fileSize);
curl_setopt($attachmentSession, CURLOPT_UPLOAD, 1);
//curl_setopt($attachmentSession, CURLOPT_POSTFIELDS, '');
curl_setopt($attachmentSession, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($attachmentSession, CURLOPT_CUSTOMREQUEST, "POST");
$curlResponse = curl_exec($curlSession);
print_r($curlResponse);

这给了我以下输出:

HTTP/1.1 100 Continue HTTP/1.1 200 OK Date: Thu, 29 Jun 2017 18:31:37 GMT Content-Type: application/json;charset=UTF-8 Content-Length: 316 Connection: close {"message":"SUCCESS","resultCode":0,"result":{"id":348293483294,"name":"smartsheet.png","attachmentType":"FILE","mimeType":"image/png","sizeInKb":85,"parentType":"ROW","parentId":32423423423,"createdBy":{"name":"Test","email":"test@test.com"},"createdAt":"2017-06-29T18:31:37Z"},"version":404}

如何从此响应中访问与parentId关联的值?我尝试了以下方法:

$curlResponse->parentId

$curlResponse[parentId]

但那些没有用。

1 个答案:

答案 0 :(得分:2)

curl返回的响应主体包含"原始http响应",包括标题和正文。 您可以通过

丢弃标题
curl_setopt($attachmentSession, CURLOPT_HEADER, false);

通过这种方式,您只能获得相应的身体,您可以json_decode。 但请注意,丢弃标题可能会在以后损害您,例如如果您需要检查某些回复。 您可以使用CURLOPT_HEADERFUNCTION获取标头,这允许您设置回调函数来解析响应标头