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 dump the response out onto the page. However, there is a quick fix for this.


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:

If you run the snippet above, you will see that the output from the request is outputted directly. However, what if we wanted to assign the output to a variable instead?

Well, thankfully it’s pretty simple:

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.

And that’s it! Hopefully, this solved your issue!

Facebook Comments