user13286
user13286

Reputation: 3085

PHP - Get specific value from curl_exec

I am doing some API work using cURL. I am logging out the session response like this:

$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);

This gives me the following output:

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":"[email protected]"},"createdAt":"2017-06-29T18:31:37Z"},"version":404}

How can I access the value associated with parentId from this response? I tried the following:

$curlResponse->parentId

and

$curlResponse[parentId]

but those didn't work.

Upvotes: 0

Views: 464

Answers (1)

Danny Yeshurun
Danny Yeshurun

Reputation: 397

The response body returned from curl contains the "raw http response", including headers and body. You can discard the headers by

curl_setopt($attachmentSession, CURLOPT_HEADER, false);

This way you will only get the respone body and you can json_decode it. Note however that discarding headers may hurt you later, e.g. if you will need to check certain responses. You can obtain the headers using CURLOPT_HEADERFUNCTION which allows you to set a callback function to parse the response headers

Upvotes: 2

Related Questions