0

Possible Duplicate:
PHP code to convert a MySQL query to CSV

i'm trying to export a csv file and i'd need to create space between the fields of the database printed because everything comes as a simple row.

What i need to do is also print in the header the name of the field.. here is the code i have. First i need to export fields in a csv tab or just space between fields...

if ( !$result1 ) { echo mysql_error(); }
while ($row = mysql_fetch_array($result1)) {
    $last = end($row);
    foreach ($row as $item) {
        fwrite($fh, $item);
        if ($item != $last)
            fwrite($fh, "\t");
    }
    fwrite($fh, "\n");
}
fclose($fh);
Community
  • 1
  • 1
Gazeta Almedicus
  • 52
  • 1
  • 1
  • 7

2 Answers2

3

You might consider using fputcsv instead of this hassle with fwrite. The syntax is like this:

int fputcsv ( resource $handle , array $fields [, string $delimiter = ',' [, string $enclosure = '"' ]] )

For your code it would look like:

$fh = fopen('file.csv', 'w');
if ( !$result1 ) { echo mysql_error(); }
while ($row = mysql_fetch_array($result1)) {
    fputcsv($fh, $result1, ',');
}
fclose($fh);

The optional $enclosure parameter can be used if you need to use other quotes for the string values (double quotes is standard).

Nick
  • 6,316
  • 2
  • 29
  • 47
Martin Müller
  • 2,565
  • 21
  • 32
  • Hey thanks for the reply...when i insert your code it gives me this result.. fputcsv() expects parameter 1 to be resource, boolean given – Gazeta Almedicus Jun 20 '12 at 11:29
  • hi, this is just an example. be sure that $fh is your actual file pointer pointing to the file you opened with fopen. also be aware i put another fopen into the text to make it better understandable for others to see what $fh is in this example. – Martin Müller Jun 20 '12 at 11:32
-1

Try this in foreach


fwrite($fh, $item.',');

Have a look at http://net.tutsplus.com/tutorials/php/how-to-generate-a-complete-excel-spreadsheet-from-mysql/

Abhishek
  • 689
  • 3
  • 14