This more or less does exactly what it says on the tin: parse CSV into a PHP array. It has serveral advantages over fgetcsv, such as, even if auto_detect_line_endings is set as false in php.ini, it can still cope with all Windows, Mac and *nix line breaks. As basslines at gmail dot com says, it also can't cope with the PHP escape character in the CSV, while this can. That's all I can think of off the top of my head...
To call the function, you can use something like easy_csv (file_get_contents('2005.csv')); if your CSV uses the default "," delimiter and is at 2005.csv, to specify a non-default delimiter, you would use something like easy_csv (file_get_contents('2005.csv'), ';'); if you're CSV uses the ";" delimiter.
You can, of course, put the CSV directly in the function, like easy_csv ('Australia, Malaysia, Bahrain, San Marino, Spain, Monaco');
As for the code itself, here you go:
<?php // Define the function easy_csvfunction easy_csv ($csv, $delimiter = ',') { // If it's got a \n line break (Windows style) then seperate lines into an enumerated arrayif (strpos($csv, "\r\n")) {$csv_lines = explode("\r\n", $csv); // If it's got a \r line break (Mac style) then seperate lines into an enumerated array} elseif (strpos($csv, "\r")) {$csv_lines = explode("\r", $csv); // If it's got a \n line break (*nix style) then seperate lines into an enumerated array} elseif (strpos($csv, "\n")) {$csv_lines = explode("\n", $csv); // If it's not got any of the above line breaks, then just dump the whole thing into $cvs_lines} else {$csv_lines = $csv;} // If $cvs_lines is an array (aka. has more than one line)if (is_array($csv_lines)) { // Set $i to 0$i = 0; // Loop through the linesforeach ($csv_lines as $csv_line) { // Put each piece of data as part of the array$csv_lines[$i] = explode($delimiter, $csv_line); // Add 1 to $i$i++; // End foreach ($csv_lines as $csv_line)} // If it isn't an array (aka. has one line)} else { // Put each piece of data as part of the array$csv_lines = explode($delimiter, $csv_lines);} // Return the array of datareturn $csv_lines; // End the function easy_csv} ?>
It produces an array like:
Array
(
[0] => Array
(
[0] => Australia
[1] => Malaysia
[2] => Bahrain
[3] => San Marino
[4] => Spain
[5] => Monaco
[6] => Europe
[7] => Canada
[8] => USA
[9] => France
)
[1] => Array
(
[0] => Britain
[1] => Germany
[2] => Hungary
[3] => Turkey
[4] => Italy
[5] => Belgium
[6] => Brazil
[7] => Japan
[8] => China
[9] => Total
)
)
Comments
There aren't any comments yet, but feel free to leave one regardless.