Search code examples
phpmysqlcsvselect-into-outfile

CSV export without MYSQL FILE functions


i'd like to make an export into CSV format, but the mutualised host i use has deactivate the FILE functions in mysql.

I did a simple SELECT and then a fopen and fwrite with PHP.

The problem is that in fields there is carriage returns or double quotes.

How to keep them and build a correct csv file?

Thanks a lot.


Solution

  • To build a best CSV. you can do following way.

       $filename ='data.csv';
       $csv_terminated = "\n";
       $csv_separator = ",";
       $csv_enclosed = '"';
       $csv_escaped = "\\";
    
    $results  = array('1','2','3');// value
    
        $schema_insert = '';
    
        $header = array('a','b','c');// header
    
    
        for ($i = 0; $i< count($header); $i++)
        {
            $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
                stripslashes($header[$i])) . $csv_enclosed;
            $schema_insert .= $l;
            $schema_insert .= $csv_separator;
        } // end for
    
        $out = trim(substr($schema_insert, 0, -1));
        $out .= $csv_terminated;
    
        // Format the data
        for($i=0;$i<count($results);$i++)
        {
            $row = $results[$i];
            $schema_insert = '';
            for ($j = 0; $j < count($header); $j++)
            {
                if ($row[$j] == '0' || $row[$j] != '')
                {
    
                    if ($csv_enclosed == '')
                    {
                        $schema_insert .= $row[$j];
                    } else
                    {
                        $schema_insert .= $csv_enclosed .
                        str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
                    }
                } else
                {
                    $schema_insert .= 'NULL';
                }
    
                if ($j < count($header) - 1)
                {
                    $schema_insert .= $csv_separator;
                }
            } // end for
    
            $out .= $schema_insert;
            $out .= $csv_terminated;
        } // end while
    
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Length: " . strlen($out));
        // Output to browser with appropriate mime type, you choose <img src="http://thetechnofreak.com/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley">
        header("Content-type: text/x-csv");
        //header("Content-type: text/csv");
        //header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=$filename");
        echo $out;
    

    Notice that, + when you make enclosed for description which has html code , you should use double quote. + Empty value --> Change to Null text or Zero value

    They will make your CSV better.