Roland
Roland

Reputation: 9701

Exporting CSV | Weird Behaviour

So, I think that I have asked this question and others related to it for more than twice. But I cannot figure out what's happening.

I'm using this PHP function to export some data from a table to a CSV table. I am testing on local host ( XAAMP ):

// Export CSV By User Level
public function CSVData($path, $level) {

    switch ($level) {
        case 0:
            $filename = $path."/standard_members_".date('Y')."_".date('m')."_".date('d').".csv";
            break;
        case 1:
            $filename = $path."/special_members_".date('Y')."_".date('m')."_".date('d').".csv";
            break;
        case 2:
            $filename = $path."/admin_members_".date('Y')."_".date('m')."_".date('d').".csv";
            break;
        default:
            break;
    }


    $sql = "SELECT user_name, user_username, user_email, user_register_date INTO OUTFILE '$filename' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' FROM users WHERE user_level = '$level'";

    if ($stmt = $this->connect->prepare($sql)) {    
        if(!($stmt->execute())){
            print_r($stmt->error);
        }
        $stmt->close();
    } else {
        $error              = true;
        $message['error']   = true;
        $message['message'] = CANNOT_PREPARE_DATABASE_CONNECTION_MESSAGE;
        return json_encode($message);
    }


    if(!is_file($filename)) {
        die('file not found');
    } else {
        header('Content-Type: application/csv');
        header("Content-Disposition: attachment; filename=$filename");
        header('Expires: 0');
        header('Pragma: no-cache');
        readfile($filename);
    }

}

And I have a form that performs the action, I mean it submits the action to the PHP file which processes the above function, and this is the action code:

<?php

    include '../assets/class/login/loginsys.php';

    $extension = new extension; 

    if ($_GET['action'] == 0) {

        $extension->CSVData('exports', 0);

    } elseif ($_GET['action'] == 1) {

        $extension->CSVData('exports', 1);

    } elseif ($_GET['action'] == 2) {

    $extension->CSVData('exports', 2);

    }

    exit();

?>

What happens is the following:

-when I click the submit button on the form I have it sends either the value 0, 1 or 2 to the action code; -the action code gets the value and processes accordingly; -but if I haven't created the folder 'exports' on localhost if would have given me this error:

Can't create/write to file 'C:xampphtdocsloginadminexports\standard_members_2012_01_28.csv' (Errcode: 2);

-and I have created it so it can work; -now that the folder it's there the CSV file is created and the data is dumped into the CSV table; -but the file that opens in my browser ( the attachment that downloads like you'd click on a file from some website and downloaded it ) it's empty even though the file exported in 'exports' has the data in it; -and another thing is that when the file already exists in the folder 'exports' the table that is created is tells me:

File 'exports/admin_members_2012_01_29.csv' already exists

So my question is why is what I described happening ? And is there a way to make the MySql query overwrite the previous CSV file ?

Upvotes: 0

Views: 827

Answers (1)

Sim
Sim

Reputation: 2725

You don't need that temporary file. How about this:

define('CSV_SEPARATOR', ',');

// CSV download headers
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="my.csv"');

// A file handle to PHP output stream
$fp = fopen('php://output', 'w');

// UTF-8 BOM
echo "\xEF\xBB\xBF";

// Get data from database
$data = ...;

// List of columns
$columns = array(
  'User name',
  'First name',
  'Last name'
);

foreach ($data as $key => $row) {

  // Write columns
  if ($key == 0) {
    fputcsv($fp, $columns, CSV_SEPARATOR);
  }

  // Write data
  fputcsv($fp, $row, CSV_SEPARATOR);
}

fclose($fp);

Beautiful, isn't it?

Upvotes: 1

Related Questions