Solved

Where is my data on my csv file?

Posted on 2014-10-08
4
111 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 110

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 110

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: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

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

Suggested Solutions

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

685 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