Where is my data on my csv file?

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);
brucegustPHP DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Beverley PortlockCommented:
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
GaryCommented:
<?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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
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
Ray PaseurCommented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.