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);
0

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks for the reply...when i insert your code it gives me this result.. fputcsv() expects parameter 1 to be resource, boolean given
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.
-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/

2 Comments

Hey abhi thank you, this worked :) If it's not much to ask, i need to print in the csv file even the headers.. i mean the table field names.. how can i do it
Huh, i just noticed it duplicates the output... i mean it works fine, the space but it duplicates...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.