title: Make cURL write data as it receives it
body: <p>I have the following php code which I found <a href="http://davidwalsh.name/download-urls-content-php-curl" rel="nofollow noreferrer">here</a>:</p>
  
  <pre><code>function download_xml()
  {
      $url = 'http://tv.sygko.net/tv.xml';
  
      $ch = curl_init($url);
      $timeout = 5;
  
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  
      $data = curl_exec($ch);
  
      echo("curl_exec was succesful"); //This never gets called
  
      curl_close($ch);
      return $data;
  }
  
  $my_file = 'tvdata.xml';
  $handle = fopen($my_file, 'w');
  $data = download_xml();
  fwrite($handle, $data);
  </code></pre>
  
  <p>What I'm trying to do is to download the xml at the specified url and save it to the disk. However, it stops once about 80% finished and never reaches the <code>echo</code> call after the <code>curl_exec</code> call. I'm not sure why, but I believe this is because it runs out of memory. Therefore I would like to ask if it is possible to make curl write the data to the file every time it has downloaded say 4kb. If this is not possible, do anybody know a way to get the xml file stored at the url downloaded and stored on my disk using php?</p>
  
  <p>Thank you very much,
  BEN. </p>
  
  <p><strong>EDIT:
  This is the code now, it doesnt work. It writes the data to the file but still only about 80% of the document. Maybe it isn't because it exceeds memory but some other reason? I really can't believe it is this hard to copy a file from a URL to the disc...</strong></p>
  
  <pre><code>    &lt;?
  
  $url = 'http://tv.sygko.net/tv.xml';
  $my_file = fopen('tvdata.xml', 'w');
  
  $ch = curl_init($url);
  $timeout = 300;
  
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_FILE, $my_file);
  curl_setopt($ch, CURLOPT_FAILONERROR, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
      curl_setopt($ch, CURLOPT_BUFFERSIZE, 4096);
  
  curl_exec($ch) OR die("Error in curl_exec()");
  
  echo("got to after curl exec");
  
  fclose($my_file);
  curl_close($ch);
  
      ?&gt;
  </code></pre>