Programming Tutorials

PHP code to write to a CSV file for Microsoft Applications

By: Soapergem @ gmail . com in PHP Tutorials on 2014-10-06  

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

?>





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

Using Text file as database in PHP

Send push notifications using Expo tokens in PHP

PHP ./configure RESULTING IN __rcp_thread_destroy@GLIBC_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

Using class within a function in PHP

Convert IP address to integer and back to IP address in PHP

Convert a hex string into a 32-bit IEEE 754 float number in PHP

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

GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP

PHP file upload with IIS on windows XP/2000 etc

instanceof OPERATOR in PHP

Appending One Array to Another in PHP

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

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Removing Duplicate Elements from an Array in PHP

Strings in PHP

Latest Articles (in PHP)