Solved

Where is my data on my csv file?

Posted on 2014-10-08
4
110 Views
Last Modified: 2014-10-09
This works:

$fpw= fopen('file.csv', 'w');

			// output the column headings
			//fputcsv($fpw, array('actor id','actor display name', 'posted time', 'display name', 'latitude', 'longitude', 'location', 'date'));

			while($row=mysqli_fetch_assoc($dan_query))
			{
			fputcsv($fpw, $row);
			}
		fclose($fpw);
		header("Location:file.php");
		exit();

Open in new window


It works as far as there being data when I manually go out to the file and open it up. When I access the file using my "file.php" page, I get the prompte to download it but when I open it up, there's no data.

What am I doing wrong?

This is the code on file.php page:


error_reporting(E_ALL);

$filename="file.csv";
header('Content-type:application/csv');
header('Content-Disposition: attachment; filename='.$filename);
0
Comment
Question by:brucegust
  • 2
4 Comments
 
LVL 34

Assisted Solution

by:Beverley Portlock
Beverley Portlock earned 100 total points
ID: 40369208
Here is some working code that I use to download CSV files

          ob_clean();

          header("Content-type: application/vnd.ms-excel");
          header("Expires: 0");
          header("Cache-Control: must-revalidate, post-check=0,pre-check=0");
          header("Pragma: public");
          header("Content-Disposition: attachment; filename=\"$filename\"");

          
          $file = file_get_contents( "$filename" );
          echo $file;
          exit;

Open in new window


The ob_clean() is not needed if you are not using output buffering (I usually do use it) but the key difference that I see is that I load the CSV and then output it into HTML output stream with an echo and I then stop the script.

It is very important that no other output than the CSV injection occurs
. If anything else is output it will either mess up the download or else appear as data.
0
 
LVL 58

Accepted Solution

by:
Gary earned 100 total points
ID: 40369273
<?php
$filename="file.csv";
header('Content-type:application/csv');
header('Content-Length: '.filesize($filename));
header('Content-Disposition: attachment; filename='.$filename);
readfile($filename);

Open in new window

0
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 300 total points
ID: 40369368
You can force a download of almost any file with this.  If you downloaded an empty file, you might want to go back and look to see if the program that created the file actually worked!

<?php // demo/temp_brucegust_download.php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('log_errors',     TRUE);


// DEMONSTRATE HOW TO CAUSE A FILE DOWNLOAD


// REQUIRED FOR USE WITH THE PHP date() FUNCTIONS
date_default_timezone_set('America/New_York');

// A FILE TO DOWNLOAD - THIS LINK COULD COME IN THE URL VIA $_GET, OR COULD BE GENERATED INSIDE THE SCRIPT
$url = "http://www.IcoNoun.com/demo/storage/brucegust.csv";

// THE USE CASE FOR THE FUNCTION
force_download($url);


// FUNCTION TO FORCE A DOWNLOAD FROM A FILE
function force_download($url, $filename=NULL)
{
    // GET THE DOWNLOAD FILE NAME
    if (empty($filename)) $filename = basename($url);

    // GET LENGTH AND FILE RESOURCE POINTER
    $hdr = get_headers($url, TRUE);
    $len = trim($hdr['Content-Length']);
    $fpr = fopen($url,'rb');

    // ON SUCCESS
    if ($fpr)
    {
        // THESE HEADERS ARE USED ON ALL BROWSERS
        header("Content-Type: application-x/force-download");
        header("Content-Disposition: attachment; filename=$filename");
        header("Content-length: $len");
        header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");

        // THIS HEADER MUST BE OMITTED FOR IE 6+
        if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
        {
            header("Cache-Control: no-cache, must-revalidate");
        }

        // THIS IS THE LAST HEADER
        header("Pragma: no-cache");

        // FLUSH THE HEADERS TO THE BROWSER
        flush();

        // WRITE THE FILE
        fpassthru($fpr);
    }

    // ERROR
    else
    {
        trigger_error("ERROR: UNABLE TO OPEN $url", E_USER_ERROR);
    }
}

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 40369372
Sidebar note:  You do not control the file suffix associations on the client browser.  Most clients will probably associate .CSV files with Excel or with a text editor.  Your choice for the file format and file suffix should be made with the idea that it would be easy for the client to use the file.  Since we don't know what your client is going to do with the file, it's hard to make a recommendation, but there are other formats for data sharing, notably XML and JSON.  You might want to consider one of those, too.  You might also want to consider exposing an API that lets the client get the file in the format they desire.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question