PHP code to write to a CSV file for Microsoft Applications

By: Soapergem @ gmail . com  

I've created a function for quickly generating CSV files that work with Microsoft applications. In the field I learned a few things about generating CSVs that are not always obvious. First, since PHP is generally *nix-based, it makes sense that the line endings are always \n instead of \r\n. However, certain Microsoft programs (I'm looking at you, Access 97), will fail to recognize the CSV properly unless each line ends with \r\n. So this function changes the line endings accordingly. Secondly, if the first column heading / value of the CSV file begins with uppercase ID, certain Microsoft programs (ahem, Excel 2007) will interpret the file as being in the SYLK format rather than CSV, as described here: http://support.microsoft.com/kb/323626

This function accommodates for that as well, by forcibly enclosing that first value in quotes (when this doesn't occur automatically). It would be fairly simple to modify this function to use another delimiter if need be and I leave that as an exercise to the reader. So quite simply, this function is used for outputting CSV data to a CSV file in a way that is safe for use with Windows applications. It takes two parameters + one optional parameter: the location of where the file should be saved, an array of data rows, and an optional array of column headings. (Technically you could omit the headings array and just include it as the first row of the data, but it is often useful to keep this data stored in different arrays in practice.)

<?php 

function mssafe_csv($filepath, $data, $header = array()) 
{ 
    if ( $fp = fopen($filepath, 'w') ) { 
        $show_header = true; 
        if ( empty($header) ) { 
            $show_header = false; 
            reset($data); 
            $line = current($data); 
            if ( !empty($line) ) { 
                reset($line); 
                $first = current($line); 
                if ( substr($first, 0, 2) == 'ID' && !preg_match('/["\\s,]/', $first) ) { 
                    array_shift($data); 
                    array_shift($line); 
                    if ( empty($line) ) { 
                        fwrite($fp, "\"{$first}\"\r\n"); 
                    } else { 
                        fwrite($fp, "\"{$first}\","); 
                        fputcsv($fp, $line); 
                        fseek($fp, -1, SEEK_CUR); 
                        fwrite($fp, "\r\n"); 
                    } 
                } 
            } 
        } else { 
            reset($header); 
            $first = current($header); 
            if ( substr($first, 0, 2) == 'ID' && !preg_match('/["\\s,]/', $first) ) { 
                array_shift($header); 
                if ( empty($header) ) { 
                    $show_header = false; 
                    fwrite($fp, "\"{$first}\"\r\n"); 
                } else { 
                    fwrite($fp, "\"{$first}\","); 
                } 
            } 
        } 
        if ( $show_header ) { 
            fputcsv($fp, $header); 
            fseek($fp, -1, SEEK_CUR); 
            fwrite($fp, "\r\n"); 
        } 
        foreach ( $data as $line ) { 
            fputcsv($fp, $line); 
            fseek($fp, -1, SEEK_CUR); 
            fwrite($fp, "\r\n"); 
        } 
        fclose($fp); 
    } else { 
        return false; 
    } 
    return true; 
} 

?>



Archived Comments


Most Viewed Articles (in PHP )

A Basic Example using PHP in AWS (Amazon Web Services)

Password must include both numeric and alphabetic characters - Magento

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Reading and Writing .gz files in PHP

PHP file upload with IIS on windows XP/2000 etc

Exception in module wampmanager.exe at 000F15A0 in Windows 8

Upload and Download files with FTP in PHP

PHP ./configure RESULTING IN [email protected]_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

Encrypting files using GnuPG (GPG) via PHP

PHP 5.1.4 INSTALLATION on Solaris 9 (Sparc)

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Installing PHP 5.x with Apache 2.x on HP UX 11i and configuring PHP 5.x with Oracle 9i

Cannot load /usr/local/apache/libexec/libphp4.so into server: ld.so.1:......

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

Function to sort array by elements and count of element in PHP

Latest Articles (in PHP)

Comment on this tutorial