CSV export thing

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi all

I am looking at the fputcsv function for something that I need.  In summary,
this is what I want to do:

1.  Go through a table
2.  Get all the columns and put them into an array
3.  write the array to a CSV file
4.  Go to the next row
5.  Append the table row into the CSV file
6.  Repeat for each row in the table

The php site shows this:


$list = array (

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

foreach ($list as $line) {
   fputcsv($fp, split(',', $line));


I'm assuming that I need the 'a+' mode for opening the file and not 'w'?

I'm ashamed to say that I have no idea how to loop through the table and put
the columns into the array.

What I'm coming up with at the moment is this:

<?php do {

$list = array (

$fp = fopen('/path/to/the/file.csv', 'a+');

foreach ($list as $line) {
   fputcsv($fp, split(',', $line));


} while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>

Probably very inelegant!

Does it look right though?


Re: CSV export thing

Andy Jacobs wrote:
Quoted text here. Click to load it

The following was adapted from

$header = '';

$data   = '';

$export = @mysql_query("SELECT * FROM $tb") or die(mysql_error());

$column_count = @mysql_num_fields($export) or die(mysql_error());

for($i = 0; $i < $column_count; $i++){
    $header .= @mysql_field_name($export, $i)."\t";

while($row = @mysql_fetch_row($export)) {
     $line = '';
     foreach($row as $value) {
         if ((!isset($value)) OR ($value == '')) {
             $value = "\t";
             $value = str_replace('"', '""', $value);
             $value = '"'.$value.'"'. "\t";
         $line .= $value;
     $data .= trim($line)."\n";

$data = str_replace("\r", '', $data);

if($data == ''){
     $data = "\n(0) Records Found!\n";

@header("Content-type: application/octet-stream");
@header("Content-Disposition: attachment; filename=$tb.xls");
@header("Pragma: no-cache");
@header("Expires: 0");
print "$header\n$data";

Re: CSV export thing

Andy Jacobs contained the following:

Quoted text here. Click to load it

Looks a bit long winded unless I'm missing summat.

How about something like:

//if not appending to existing file
$csv= "firstname,lastname,email,telephone\n";

 while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)){
$csv.=implode(",", $row_Recordset1)."\n";

Then just write $csv to a file.

Untested, obviously.

Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker /

Site Timeline