Solved

Where is my data on my csv file?

Posted on 2014-10-08
4
118 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

Question has a verified solution.

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

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses how to implement server side field validation and display customized error messages to the client.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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.

628 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