Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Convert a comma separated file into an associated array.

View csv_to_array.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
<?php
/**
* Convert a comma separated file into an associated array.
* The first row should contain the array keys.
*
* Example:
*
* @param string $filename Path to the CSV file
* @param string $delimiter The separator used in the file
* @return array
* @link http://gist.github.com/385876
* @author Jay Williams <http://myd3.com/>
* @copyright Copyright (c) 2010, Jay Williams
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
/**
* Example
*/
print_r(csv_to_array('example.csv'));
?>
View csv_to_array.php
1 2 3
"name", "number"
"Lorem", 11
"ipsum", 22
View csv_to_array.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Array
(
[0] => Array
(
[name] => Lorem
[number] => 11
)
 
[1] => Array
(
[name] => ipsum
[number] => 22
)
 
)

Very useful! thanks!

Nice dude, works perfectly.

Great work!!!

BOOM! brilliant.

stigs commented

Fantastic! Just what I was looking for. Thanks for the link over on the php documentation!

awesome! just what i need! Thanks for sharing!

Sorry if it should be obvious. How do I use this? I had a play and didn't get an echo to work to check I had it set up right or even begin to use the data. Do I need to link to any other files other than my csv?

Got it too work with some help from a friend. I had simply put an absalute path hhtp localhost/.../example.csv in worked fine once I put a relative one in. Great work

Beautiful. Avoided a real "head scratcher"!

Here is a (somewhat inefficient) revision which deals with multiple identically-named headers (for example: "User","Name","Name" becomes "User","Name","Name2"):

function csv_to_array($filename='', $delimiter=',')
{
    if(!file_exists($filename) || !is_readable($filename))
    {
        return FALSE;
    }
    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 0, $delimiter)) !== FALSE)
        {
            if(!$header)
            {
                $header = array();
                foreach ($row as $val)
                {
                    $header_raw[] = $val;
                    $hcounts = array_count_values($header_raw);
                    $header[] = $hcounts[$val]>1?$val.$hcounts[$val]:$val;
                }
            }
            else
            {
                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}

thanks for the script. works great. here is a version adjusted to handle csv files with rows that have fewer columns than the header row. adds delimiter(s) to the end of shorter shows so the file can still be read.

function csv_to_array($filename='', $delimiter=',') {

    ini_set('auto_detect_line_endings',TRUE);
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;

    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if (!$header) {
                $header = $row;
            }
            else {
                if (count($header) > count($row)) {
                    $difference = count($header) - count($row);
                    for ($i = 1; $i <= $difference; $i++) {
                        $row[count($row) + 1] = $delimiter;
                    }
                }
                $data[] = array_combine($header, $row);
            }
        }
        fclose($handle);
    }
    return $data;
}

Thanks for that :)

thanks , i use one of them

@tbradley22, solid this worked for me as well!

Perfect, thanks!

tbradley22 comment helped alot thanks.

perfect, thanks!

Thank you, this was handy.

which is the line of the code in which the first line of the csv file is identified as the titles of each column?.
thank you very much this has been very useful to me.

This PHP script allows you to export and download CSV http://webtricksandtreats.com/export-to-csv-php

Thanks @tbradley22 it's excactly what I needed.

https://gist.github.com/jaywilliams/385876#file-csv_to_array-php-L28
replace this
$header = $row;
to this:
$header = array_map('trim', $row);

Thanks dude, works perfectly. ;)

I encounter rather a lot of csv files that lack header rows.

If your file lacks a header row, here's a simple way to deal with either case. If there is a header row, leave the fieldnames parameter blank... if it lacks a header row, pass a comma-delimited list of field names.

function csv_to_array($filename='', $delimiter=',', $fieldnames='')
{
    if(!file_exists($filename) || !is_readable($filename))
        return FALSE;
    if(strlen($fieldnames) > 0) {
        $header = explode(",",$fieldnames);
    } else {
        $header = NULL;
    }
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
        {
            if(!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }
    return $data;
}

Perfect ......

Thanks @rboatright

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.