PHP: Return cURL response as a string.

This is a short PHP tutorial on how to return cURL output as a string.

As you probably already know, the default behavior of cURL is to simply print the response out onto the page.

However, there is a quick fix for this.

The CURLOPT_RETURNTRANSFER option.

The curl_setopt function allows you to configure various options for a cURL request.

One such option that we can set with this function is CURLOPT_RETURNTRANSFER.

Take the following PHP code as an example:

//Create a cURL handle.
$ch = curl_init('http://test.com');

//Execute the cURL transfer.
$result = curl_exec($ch);

If you run the snippet above, you will see that the output from the request is printed out directly into the browser.

However, what if we wanted to assign the output to a variable instead?

Well, thankfully it’s pretty simple:

//Create a cURL handle.
$ch = curl_init('http://test.com');

//Set CURLOPT_RETURNTRANSFER to TRUE
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Execute the cURL transfer.
$result = curl_exec($ch);

In the example above, we set CURLOPT_RETURNTRANSFER to TRUE before we executed the cURL request.

Note how I emphasized the word “before” there. This option must be configured before the cURL transfer is executed.

As a result, the curl_exec function will now return the response as a string instead of outputting it.