89

I am using the following code:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_TIMEOUT, 12); 

$result = curl_exec($ch);

curl_close ($ch);

However it's printing the results straight away. Is it possible to put the JSON result into a variable so I can print it out when I want to?

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Oliver Bayes-Shelton
  • 6,135
  • 11
  • 52
  • 88

3 Answers3

201

Set CURLOPT_RETURNTRANSFER option:

// ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$result = curl_exec($ch);

Per the docs:

CURLOPT_RETURNTRANSFER - TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Kel
  • 7,680
  • 3
  • 29
  • 39
  • 2
    Your linked doc says "From PHP 5.1.3, this option has no effect: the raw output will always be returned when CURLOPT_RETURNTRANSFER is used". I am not quite sure that I understand that, being a Mawg of very little brain, and I still have the same problem as O.P – Mawg says reinstate Monica May 29 '14 at 16:45
  • 3
    Looks like this note in PHP documentation is related to CURLOPT_BINARYTRANSFER option, not CURLOPT_RETURNTRANSFER option. – Kel Jun 17 '14 at 21:20
4

Have you tried?

curl_setopt($ch, CURLOPT_VERBOSE, 0);

This worked for me!

Joe
  • 4,877
  • 5
  • 30
  • 51
-8

after php 5.1 curl will display always result you can view in documentation. for avoid it simply use

echo "< span style='display:none'>";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_TIMEOUT, 12);

$result = curl_exec($ch);

curl_close ($ch);

echo"< /span>";
Ankur Bhadania
  • 4,123
  • 1
  • 23
  • 38
user3443146
  • 71
  • 1
  • 2
  • 6
  • 4
    `curl`'s behaviour is configurable, but if you really come across something that can't be configured to return the value instead of printing it, you should really use `ob_start()` before you call it, and `ob_get_clean()` after. The return value of `ob_get_clean()` will be the content that otherwise would've been printed. Take a look at the documentation of these functions to learn about them. Your answer is really not decent, so I thought you might learn from these. Didn't mean to offend you. Good luck! – Tamás Barta Feb 24 '15 at 16:19
  • 3
    Actually the problem with this answer (besides the points the previous commenter mentioned) is that it doesn't answer the question. It hasn't been mentioned if it is a web application or not, so you cannot be sure how output is displayed (it could even be a console application). – mark.sagikazar Feb 24 '15 at 16:27