title: How to download a temporary file
body: <p>I'm trying to create a short PHP script that takes a JSON string, converts it to CSV format (using <code>fputcsv</code>), and makes that CSV available as a downloaded .csv file.  My thought was to use <code>tmpfile()</code> to not worry about cronjobs or running out of disk space, but I can't seem to make the magic happen.</p>
  
  <p>Here's my attempt, which is a converted example from <a href="http://php.net/manual/en/function.readfile.php#refsect1-function.readfile-examples" rel="noreferrer">the PHP docs of <code>readfile</code></a>:</p>
  
  <pre><code>$tmp = tmpfile();
  $jsonArray = json_decode( $_POST['json'] );
  fputcsv($tmp, $jsonArray);
  
  header('Content-Description: File Transfer');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename='.basename($tmp));
  header('Content-Transfer-Encoding: binary');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize($tmp));
  
  ob_clean();
  flush();
  readfile($tmp);
  </code></pre>
  
  <p>I feel like the <code>Content-Disposition</code> and <code>Content-Transfer-Encoding</code> headers are wrong, but I'm not sure how to fix them.  For example, <code>basename($tmp)</code> doesn't seem to return anything, and I'm not sure <code>text/csv</code> transfers as binary encoding. Likewise, <code>echo filesize($tmp)</code> is blank as well.  Is there a way to do what I'm attempting here?</p>
  
  <p><strong>[Edit]</strong></p>
  
  <p>**Below is the working code I wrote as a result of the accepted answer:*</p>
  
  <pre><code>$jsonArray = json_decode( $_POST['json'], true );
  $tmpName = tempnam(sys_get_temp_dir(), 'data');
  $file = fopen($tmpName, 'w');
  
  fputcsv($file, $jsonArray);
  fclose($file);
  
  header('Content-Description: File Transfer');
  header('Content-Type: text/csv');
  header('Content-Disposition: attachment; filename=data.csv');
  header('Content-Transfer-Encoding: binary');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');
  header('Content-Length: ' . filesize($tmpName));
  
  ob_clean();
  flush();
  readfile($tmpName);
  
  unlink($tmpName);
  </code></pre>