0

This is the SQL query

$query = "SELECT col1,col2,col3,col4,col5,col6,col7,col8 FROM table;
if (!$result = mysqli_query($con, $query))
{
    exit(mysqli_error($con));
}

This is the part that outputs the text file

$filename = "output.txt";
$file = fopen($filename, "w");
foreach ($result as $rows)
{
    fwrite($file, implode("\t",$rows).PHP_EOL);
}

header('Content-Description: File Transfer');
header('Content-type: text/tab-separated-values');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;

This is the current output:
This is the current output This is the output that I need:
This is the output that I need

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • The simplest solution might be to write the data into an html table. – Wesley Smith Oct 05 '20 at 07:49
  • You can use CSV (Comma Separated Values) format instead. The CSV common used file format – Slava Rozhnev Oct 05 '20 at 07:53
  • Use CONCAT / CONCAT_WS and retrieve not 8 separate columns but ready-to-use 8-column HTML table row or tab-delimited / space-justified text. – Akina Oct 05 '20 at 08:02
  • It is a very bad idea to use `exit(mysqli_error($con))` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Oct 05 '20 at 10:41

1 Answers1

0

As commented out by @Slava Rozhnev and best way is to use csv like this:

<?php

$query = "SELECT col1,col2,col3,col4,col5,col6,col7,col8 FROM table";
$result = mysqli_query($con, $query);

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

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

fclose($fp);
Sumit Wadhwa
  • 2,825
  • 1
  • 20
  • 34