BigToach.com

PHP Snippets

csv2array

Information

(PHP Version >= 3)
Functions used in this snippet: file_exists, is_readable, file_get_contents, preg_replace, explode, array_map, unset, range, count, substr_count, reset.

Description

array csv2array( string file, boolean titles )

Takes a csv file and turns it into a multidimensional array. If you leave titles set to true it returns the array with the first line as the associative indexes of the array, if you set titles to false the first line is included in the values and the indexes are integers.

array2csv returns false if the file is not found or not readable.

Snippet

<?php
function csv2array($file$titles=true)
{
    if(!
file_exists($file) || !is_readable($file))
    {
        return 
false;
    }
    
$file file_get_contents($file);
    
$file preg_replace("/(\r\n|\r|\n\n)/ms""\n"$file);
    
$lines explode("\n"$file);
    if(
$titles)
    {
        
$titles array_map('trim'explode(',',$lines[0]));
        unset(
$lines[0]);
    }
    else 
    {
        
$titles range(0count(explode(','$lines[0]), 1));
    }
    
$return = array();
    foreach(
$lines as $key => $line)
    {
        
$peices array_map('trim'explode(','$line));
        for(
$i=0;$i<count($peices);$i++)
        {
            
$k $i;
            while(
substr_count($peices[$k], '"') % === 1)
            {
                
$peices[$k] = $peices[$k] . ',' $peices[$i 1];
                
$i++;
                unset(
$peices[$i]);
            }
        }
        
reset($peices);
        foreach(
$peices as $column => $peice)
        {
            
$return[$titles[$column]][$key] = $peice;
        }
    }
    return 
$return;
}
?>

Example

csv2array Can be used in the following way:

<?php
<?php
/* In the example the csv is as follows:
Name,Title
Scott Roach,"Web Developer, CCi"
Annie Roach,Production Designer
*/

$csv csv2array('file.csv');
print_r($csv);
/*
Array(
    [Name] => Array(
        [0] => Scott Roach
        [1] => Annie Roach
    )
    [Title] => Array(
        [0] => Web Developer, CCi
        [1] => Production Designer
    )
)
*/
$csv csv2array('file.csv'false);
print_r($csv);
/*
Array(
    [0] => Array(
        [0] => Name
        [1] => Scott Roach
        [2] => Annie Roach
    )
    [1] => Array(
        [0] => Title
        [1] => "Web Developer, CCi"
        [2] => Production Designer
    )
)
*/

$csv csv2array('non-existant-file.csv');
print_r($csv);
// False
?>

Added on Feb 21st at 4 pm by Scott - 2 Comments
Updated on Feb 21st at 4 pm.


2 Responses to csv2array

Alfred Bennett (alfbennett[at]gmail[dot]com) commented on Jan 4th at 5 pm
I got some weird results from your code.

Here is my shot at it, it worked better for me.

--------------------------

if (!function_exists('str_getcsv')) {
function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
$fiveMBs = 5 * 1024 * 1024;
$fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
fputs($fp, $input);
rewind($fp);
$data = fgetcsv($fp, 1000, $delimiter, $enclosure); // $escape only got added in 5.3.0
fclose($fp);
return $data;
}
}

function csv2array($file, $titleRow=true){
$csvData = file($file);
if($titleRow){
$titles = str_getcsv(array_shift($csvData));
}
$records = array();
foreach ($csvData as $record){
$records[] = array_combine($titles,str_getcsv($record));
}
return $records;
}
Anonymous Pansy commented on Mar 12th at 5 am
function csv_to_array($csv, $delimiter = ',', $enclosure = '"', $escape = '\\', $terminator = "\n") {
$r = array();
$rows = explode($terminator,trim($csv));
$names = array_shift($rows);
$names = str_getcsv($names,$delimiter,$enclosure,$escape);
$nc = count($names);
foreach ($rows as $row) {
if (trim($row)) {
$values = str_getcsv($row,$delimiter,$enclosure,$escape);
if (!$values) $values = array_fill(0,$nc,null);
$r[] = array_combine($names,$values);
}
}
return $r;
}

Name:

Site or Mail:

Comment:

To try to reduce the ammount of spam, please enter the word GOOSE in the following form

Security Code: