0

I am trying to save some JSON data to a local file. I am making a cUrl call to a REST service and doing the following:

$content = curl_exec( $ch );
curl_close( $ch );
$handle = fopen(time().'.txt','w');
fwrite($handle, $content);
print $content;

The file is created, but it is empty with the exception of the numeral 1. The JSON string does print out to screen without any problems, so the issue is not that I am getting an error. Any idea why this may be happening?

Answser:

I forgot to add the following to the curl call:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
4
  • Nothing in the error logs at all? Commented Jul 18, 2014 at 14:57
  • fwrite() returns the number of bytes written, or FALSE on error. - Please post the result of fwrite. Commented Jul 18, 2014 at 15:00
  • 1
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); Commented Jul 18, 2014 at 15:04
  • I wish they would add a rule to force users to state why they voted a question or an answer down. That would definitely cut down on the number of trolls. Commented Jul 18, 2014 at 22:26

2 Answers 2

1

In terms of debugging, it would be easier to print the result until you have one and then save to file after you know you have something.

Did you set the option "CURLOPT_RETURNTRANSFER" ? You need to do that to use cURL the way you are. https://www.php.net/manual/en/function.curl-setopt.php

Sign up to request clarification or add additional context in comments.

Comments

0

Some ideas to debug this:

  • replace $content with a static value (e.g.: $content = "foo";)
  • try to properly close the file by adding fclose($handle);
  • add error_reporting(0); at the beginning to be sure to see any error occurring
  • check the permissions

1 Comment

closing the file is syntactically proper, but php closes it automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.