karto
karto

Reputation: 3668

Creating a CSV file from MySQL table using php

this code creates a csv file. However, I have avoided printing out commas in the fields because it is used as a delimeter (see line 22). Now I want to remove (carriage returns and new lines) from the fields. Adding $somecontent .= str_replace("\n", "", $val); on line 23 does not seem to work. any ideas?

@chmod($export_csv, 0777);
    $fe = @fopen($export_csv."/export.csv", "w+");
    if($fe){           
        $somecontent = "";
        $fields_count = 0;
        // print field headers
        $db->query($sql_view);
        if($row = $db->fetchAssoc()){
            foreach($row as $key => $val){
                if($fields_count++ > 0) $somecontent .= ",";
                $somecontent .= ucfirst($key);
            }
        }
        $somecontent .= "\n"; 

        // print field values
        $db->query($sql_view);
        while($row = $db->fetchAssoc()){
            $fields_count = 0;
            foreach($row as $key => $val){
                if($fields_count++ > 0) $somecontent .= ",";
                $somecontent .= str_replace(",", "", $val);
                $somecontent .= str_replace("\n", "", $val);
            }
            $somecontent .= "\n";                    
        }

        // write some content to the opened file.
        if (fwrite($fe, $somecontent) == FALSE) echo 'file_writing_error'." (export.csv)"; 
        fclose($fe);
    }

Upvotes: 0

Views: 944

Answers (4)

krifur
krifur

Reputation: 890

you can try something like this, playing with ASCII caracters

$somecontent .= str_replace(CHR(10), " ", $val);
$somecontent .= str_replace(CHR(13), " ", $val); 

Upvotes: 0

Shakti Singh
Shakti Singh

Reputation: 86386

Use fputcsv function to write the CSV files. PHP already have a function to write csv files.

You do not need to handle escaping, delimiter by yourself all these already handled.

This will handle all these things for you and will save you from many headaches.

Upvotes: 2

Gordon
Gordon

Reputation: 316969

You can do that from MySql directly:

SELECT col1, col2, col3 INTO OUTFILE '/tmp/export.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test_table;

Upvotes: 1

Jaffa
Jaffa

Reputation: 12710

Where is your $somecontent .= str_replace("\n", "", $val)? I can't find it in your code.

You can specify an array as first parameter for str_replace as indicated there. Thus, it would replace each string present in your array with the second parameter.

For example, $somecontent .= str_replace(array("\n", "\r"), "", $val);

Upvotes: 0

Related Questions