1

I have this piece of PHP code that's intended to retrieve data from a mySQL database, and export it to a CSV file that has to be automatically downloaded after it was created.

$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));

// fetch mysql table rows
$sql = "select * from users";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

$fp = fopen('users.csv', 'w');

while($row = mysqli_fetch_assoc($result)) {
    fputcsv($fp, $row);
}

fclose($fp);

header('Content-Type: text/csv');

header('Content-Disposition: attachment; filename="users.csv"');

mysqli_close($connection);

The problem here is that it:

  • Retrieves the data.
  • Retrieves the CSV file on the server in the same directory of the export.php file with the data on it.
  • Downloads the file with the same name BUT it's EMPTY

Thanks.

med k
  • 11
  • 5
  • 1
    you never bothered outputting the file. you need something like `readfile('users.csv')` to read the file off-disk and spit it out to your client. – Marc B Mar 23 '16 at 16:29
  • You don't output the file contents you are only sending the name of the file and that it is a CSV. – chris85 Mar 23 '16 at 16:29
  • 1
    Rather than write it to a physical file on the server (problematic if you have concurrent users) use `'php://output'` as the filename (and send your headers before opening the file), which will send it directly to the browser without using any server disk at all – Mark Baker Mar 23 '16 at 16:37

3 Answers3

1

You're writing it to a file called users.csv, but the file you are forcing the user to download is the output of the page.

As long as your query is correct, once the PHP script has run, there should be a file called users.csv in the same directory as the PHP file that contains the correct data.

You need to output the data to the browser for it to be attributed to the file you're downloading.

Try this:

//Connect to database
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));

//Fetch mysql table rows
$sql = "select * from users";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

//Close connection
mysqli_close($connection);

//Set $output
$output = "";

//Set header values
$headers = array("Header 1", "Header 2", "Header 3");

//Insert header values to $output
foreach($headers as $h){
    $output .= fieldCheck($h) . ",";
}
$output = rtrim($output, ","). "\n";

//Iterate through results
while($row = mysqli_fetch_assoc($result)) {
    foreach($row as $cell){
        //Comma-separate each value
        $output .= fieldCheck($cell).",";
    }
    //Remove last comma of each line and add newline
    $output = rtrim($output, ",") . "\n";
}

//Set headers
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="users.csv"');

//Output
echo $output;

exit;

//Function in case of comma in field
function fieldCheck($string){
    if(strpos($string, ",") !== false){
        $string = '"'.$string.'"';
    }
    return $string;
}
Ben
  • 8,894
  • 7
  • 44
  • 80
  • this works perfect except for the separator, is there a way to make use ";" instead of "," and is there a way to add custom header for the colums? as when I add the names of columns just after $output = ""; excel tells me that the file format is different from the extension but it opens anyway. – med k Mar 23 '16 at 16:43
  • Well, CSV stands for "Comma Separated Values", so by using a semicolon `;` or tab you are making it un-openable by CSV. What you can do is create a function that, if there is a comma in the field, to enclose the field in quotation marks - I've added that into my answer. I've also added the header fields to my answer. – Ben Mar 23 '16 at 16:50
  • it always says that the type is different from what's specified by the extension. and it says also it is in SYLK format but it may has an error (my MS EXCEL is in French) – med k Mar 23 '16 at 17:23
  • without the headers it works perfect but when adding column headers it shows the error message in EXCEL but still opens – med k Mar 23 '16 at 17:26
  • Solved! Just wrapping every entry in quotation marks, no matter containing a comma or not – med k Mar 23 '16 at 17:35
0

I have seen this question come up quite a few times and here the user is sending the data to "users.csv" as shown below:

$fp = fopen('users.csv', 'w');

The issue is that unless the file "users.csv" is already created there is nothing to write the data to, so the CSV is blank. The "fopen" does not create the file it only opens an existing file and the "w" directive then instructs "fputcsv" to put it into the file "users.csv" which may not exist and if the file does exist it writes over the existing file.

Here is an explainer PHP script that will send the output (CSV) to a filename of your choice for downloading:

//Connect to database
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));
        
//Get the data
//The order and number of elements must match the header below or the data
//will appear in the wrong columns.
$sql = "SELECT FirstName,LastName,Address,City,State,Zip FROM users";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));
   
//Close connection
mysqli_close($connection);

//Name of the file you want the user to download can be any name but 
//use the .CSV file extension so it will be recognized 
//as a CSV when downloaded. 
$NameOfCSVFileToDownload = "MyCSVFile.csv";

//set headers tells the page what to do
header("Content-Type: application/csv; charset=utf-8");
header("Content-Disposition: attachment;filename=\"$NameOfCSVFileToDownload\"");

//Where to send the data - 
//there are several option but sending it to output will insert 
//the data into "$NameOfCSVFileToDownload" when complete, your output.
//Output is a way to access I/O streams 
$output = fopen("php://output", 'w');

//Add the header or 1st row for your data 
//-notice we are sending it to "$output" you can add any names you want 
//for this header row but make sure that the number of columns in the header 
//matches the number of columns you are retrieving from the database or they 
//will not line up when you open up the CSV and things will look scrambled.
fputcsv($output, array('FirstName','LastName','Address','City','State','Zip'));

//Loop through the data and insert the data into "$output"
while($rows = $result->fetch_assoc()){
fputcsv($output, $rows);
}

//Close the "$output" file to complete the write.
fclose($output);

That's all, call the page and it will prompt to open or download the CSV that contains data. If it is still blank make sure your SQL statement is actually pulling data. You can also review the PHP manual on streams to better understand. PHP Manual

user1946891
  • 955
  • 1
  • 11
  • 18
0

Combining a few ideas mentioned in the comments:

  1. Output directly to stdout (rather than a users.csv file). This prevents concurrent processes from clashing with the same output file. No need to buffer temporary results in a variable, either.

  2. Use fputcsv()'s 3rd argument to specify ';' as the field separator. No need to rewrite special code for that.

  3. Use array_map() and a custom filter to add quotes around all the fields.

// Helper function to surround a string with double quotes
function pad_with_quotes($s) {
    return '"' . $s . '"';
}

// Helper function to output a row to $fp:
function output_row($fp, $row) {
    // Separate fields with ';':
    fputcsv($fp, array_map('pad_with_quotes', $row), ';');
}

// Send HTTP headers
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="users.csv"');

// Open a pointer to stdout:
$fp = fopen('php://output', 'w'); // TO DO: check for fopen() failure

// Output headers (padded with quotes):
output_row($fp, ['foo', 'bar']); // TO DO: change headers

// DB connection/query goes here; omitted for brevity

// Loop through DB results:
while($row = mysqli_fetch_assoc($result)) {
    // Output a row of results:
    output_row($fp, row);
}
kmoser
  • 8,780
  • 3
  • 24
  • 40