简体   繁体   中英

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

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.

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;

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

you can try something like this, playing with ASCII caracters

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM