Posts Tagged ‘response’

Posted by 6bytes at 14 April 2010

Category: PHP

Tags: , ,

Recently I had a small problem with cURL. The request was supposed to return only JSON data to use in my app. I wrote the following:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://somedomain.com/api/123');
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_exec($curl);
$status = curl_getinfo($curl);
curl_close($curl);

The variable $status contained the API’s response in plain text and concatenated, inaccessible in this format, array with cURL’s status response. This made impossible for example checking if the request was successful. I had to get rid of the JSON response and leave only cURL status array. In order to do that I added curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); option which cleared all this garbage and left only cURL’s status array.

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://somedomain.com/api/123');
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_exec($curl);
$status = curl_getinfo($curl);
curl_close($curl);

Last thing I had to do was retrieve API’s JSON response and assign it to another variable. I have to say the solution wasn’t my first logical choice. After some time it turned out that curl_exec() returns exactly what I need.
In the end, my bit of code became something like this:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://somedomain.com/api/123');
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$response = curl_exec($curl);
$status = curl_getinfo($curl);
curl_close($curl);

Now, variable $response contained only JSON and $status contained only cURL’s response status. I was happy again.