PHP 7: Query output to Text File Questions (FIeld Headers and Skipping a Comma after last column) -


i've new php , trying re-create code had in language. current version of php i'm working 7.17.

right now, i'm trying re-create simple function of opening mysql query comma deliminated text file there no comma after last column (just line break). i'm trying figure out 2 things right finish piece of code.

  1. how insert query column headers @ top of data output (right data output, not column headers).

  2. at line "fwrite($output, $value.',');", i'm trying figure out how not add comma after last field (how skip adding comma after last column of data).

php:

if (isset($_post['download'])) {     header('content-type: text/plain');     header('content-disposition: attachment;filename=cars.txt');     header('cache-control: no-cache, no-store, must-revalidate');     header('pragma: no-cache');     header('expires: 0');     $output = fopen('php://output', 'w');      while ($row = getrow($result)) {         foreach ($row $key => $value) {             fwrite($output,  $value.',');         }         fwrite($output, "\r\n");     }     fclose($output);      exit;  } 

thank you!

it sounds trying create csv file, why not use php's built in csv handling functionality (fputcsv), so:

$output = fopen('php://output', 'w');  while ($row = getrow($result)) {     fputcsv($output, $row); }  fclose($output); 

this way php heavy lifting you.

edited based upon comment.

you try using answer here handle encoding of values before converting csv , set file encoding in http header header('content-type: text/plain; charset=utf-8');.

also fputcsv allows change delimiter, enclosure , escape characters if causing issues.

otherwise do:

$output = fopen('php://output', 'w');  while ($row = getrow($result)) {     $line = implode(', ', $row);     fwrite($output, $line); }  fclose($output); 

Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -