Solved

Where is my data on my csv file?

Posted on 2014-10-08
4
101 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 108

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 108

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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

746 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now