Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Convert a comma separated file into an associated array.
<?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'));
?>
name number
Lorem 11
ipsum 22
Array
(
[0] => Array
(
[name] => Lorem
[number] => 11
)
[1] => Array
(
[name] => ipsum
[number] => 22
)
)
@killua99

This comment has been minimized.

Show comment Hide comment
@killua99

killua99 Sep 2, 2011

Very useful! thanks!

killua99 commented Sep 2, 2011

Very useful! thanks!

@pippinsplugins

This comment has been minimized.

Show comment Hide comment
@pippinsplugins

pippinsplugins Jul 5, 2012

Nice dude, works perfectly.

Nice dude, works perfectly.

@espinozaulises

This comment has been minimized.

Show comment Hide comment
@espinozaulises

espinozaulises Sep 20, 2012

Great work!!!

Great work!!!

@dubrod

This comment has been minimized.

Show comment Hide comment
@dubrod

dubrod Feb 18, 2013

BOOM! brilliant.

dubrod commented Feb 18, 2013

BOOM! brilliant.

@stigs

This comment has been minimized.

Show comment Hide comment
@stigs

stigs Mar 5, 2013

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

stigs commented Mar 5, 2013

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

@cherihung

This comment has been minimized.

Show comment Hide comment
@cherihung

cherihung May 1, 2013

awesome! just what i need! Thanks for sharing!

awesome! just what i need! Thanks for sharing!

@hagatorn

This comment has been minimized.

Show comment Hide comment
@hagatorn

hagatorn May 3, 2013

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?

hagatorn commented May 3, 2013

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?

@hagatorn

This comment has been minimized.

Show comment Hide comment
@hagatorn

hagatorn May 5, 2013

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

hagatorn commented May 5, 2013

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

@stevebrush

This comment has been minimized.

Show comment Hide comment
@stevebrush

stevebrush Aug 2, 2013

Beautiful. Avoided a real "head scratcher"!

Beautiful. Avoided a real "head scratcher"!

@peckjon

This comment has been minimized.

Show comment Hide comment
@peckjon

peckjon Aug 24, 2013

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

peckjon commented Aug 24, 2013

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

This comment has been minimized.

Show comment Hide comment
@tbradley22

tbradley22 Aug 30, 2013

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 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;
}
@diego-vieira

This comment has been minimized.

Show comment Hide comment
@diego-vieira

diego-vieira Sep 19, 2013

Thanks for that :)

Thanks for that :)

@jkeks

This comment has been minimized.

Show comment Hide comment
@jkeks

jkeks Nov 20, 2013

thanks , i use one of them

jkeks commented Nov 20, 2013

thanks , i use one of them

@zanematthew

This comment has been minimized.

Show comment Hide comment
@zanematthew

zanematthew Jan 24, 2014

@tbradley22, solid this worked for me as well!

@tbradley22, solid this worked for me as well!

@ptrikutam

This comment has been minimized.

Show comment Hide comment
@ptrikutam

ptrikutam Feb 4, 2014

Perfect, thanks!

Perfect, thanks!

@CrandellWS

This comment has been minimized.

Show comment Hide comment
@CrandellWS

CrandellWS Feb 13, 2014

tbradley22 comment helped alot thanks.

tbradley22 comment helped alot thanks.

@manishie

This comment has been minimized.

Show comment Hide comment
@manishie

manishie Feb 20, 2014

perfect, thanks!

perfect, thanks!

@lordspace

This comment has been minimized.

Show comment Hide comment
@lordspace

lordspace Jun 9, 2014

@AbijeetP

This comment has been minimized.

Show comment Hide comment
@AbijeetP

AbijeetP Jun 28, 2014

Thank you, this was handy.

Thank you, this was handy.

@diegoangc

This comment has been minimized.

Show comment Hide comment
@diegoangc

diegoangc Jul 9, 2014

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.

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.

@ecorvo

This comment has been minimized.

Show comment Hide comment
@ecorvo

ecorvo Sep 2, 2014

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

ecorvo commented Sep 2, 2014

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

@RPDeshaies

This comment has been minimized.

Show comment Hide comment
@RPDeshaies

RPDeshaies Sep 19, 2014

Thanks @tbradley22 it's excactly what I needed.

Thanks @tbradley22 it's excactly what I needed.

@adisos

This comment has been minimized.

Show comment Hide comment
@adisos

adisos Oct 14, 2014

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

adisos commented Oct 14, 2014

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

@web-caos

This comment has been minimized.

Show comment Hide comment
@web-caos

web-caos Jan 4, 2015

Thanks dude, works perfectly. ;)

web-caos commented Jan 4, 2015

Thanks dude, works perfectly. ;)

@rboatright

This comment has been minimized.

Show comment Hide comment
@rboatright

rboatright Feb 19, 2015

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

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

This comment has been minimized.

Show comment Hide comment
@iqbalatblackid

iqbalatblackid Feb 24, 2015

Perfect ......

Perfect ......

@sommarnatt

This comment has been minimized.

Show comment Hide comment
@sommarnatt

sommarnatt Apr 2, 2015

Thanks @rboatright

@mokanfar

This comment has been minimized.

Show comment Hide comment
@mokanfar

mokanfar May 21, 2015

<3

<3

@Namsep

This comment has been minimized.

Show comment Hide comment
@Namsep

Namsep Sep 16, 2015

All my columns are double quotes ( "name something") and are nicely mapped. Except for the first one, which is correct in the CSV. Anyone got a clue?

[0] => "Contract Number"
[1] => Product Type
[2] => Internal Title

Namsep commented Sep 16, 2015

All my columns are double quotes ( "name something") and are nicely mapped. Except for the first one, which is correct in the CSV. Anyone got a clue?

[0] => "Contract Number"
[1] => Product Type
[2] => Internal Title
@KarelWintersky

This comment has been minimized.

Show comment Hide comment
@KarelWintersky

KarelWintersky Oct 11, 2015

Excellent. Thanx!

Excellent. Thanx!

@irfanwv

This comment has been minimized.

Show comment Hide comment
@irfanwv

irfanwv Apr 26, 2016

What if in the Name: Lorem, Ipsum
and Id: 12

irfanwv commented Apr 26, 2016

What if in the Name: Lorem, Ipsum
and Id: 12

@janepatel

This comment has been minimized.

Show comment Hide comment
@janepatel

janepatel Jun 6, 2016

Hi
If you want to convert text file into array please follow below link, on this link you can find complete code with live demo.

You can try online with link link.

Convert text file into array

Hi
If you want to convert text file into array please follow below link, on this link you can find complete code with live demo.

You can try online with link link.

Convert text file into array

@rap2hpoutre

This comment has been minimized.

Show comment Hide comment
@rap2hpoutre

rap2hpoutre Jun 9, 2016

I just made an ugly tiny version for composer / packagist (remember left-pad for JS, yolo)

composer require rap2hpoutre/csv-to-associative-array

I just made an ugly tiny version for composer / packagist (remember left-pad for JS, yolo)

composer require rap2hpoutre/csv-to-associative-array
@botaylortravismathew

This comment has been minimized.

Show comment Hide comment
@botaylortravismathew

botaylortravismathew Mar 27, 2017

This is awesome! I used it for importing large amount of data into a Wordpress ACF Repeater field. Worked great thank you very much for this.

This is awesome! I used it for importing large amount of data into a Wordpress ACF Repeater field. Worked great thank you very much for this.

@BallisticPain

This comment has been minimized.

Show comment Hide comment
@BallisticPain

BallisticPain Jun 1, 2017

@rboatright
I don't know why I didn't notice this before, but you aren't using the $delimiter passed as a parameter for the header columns. Wouldn't they usually be the same delimiter as the rest of the file?

Edit: Doh! I remember having thought about this last time. I see what it's doing now. I'm passing in the "headers" via string which is comma delimited. Thanks!

BallisticPain commented Jun 1, 2017

@rboatright
I don't know why I didn't notice this before, but you aren't using the $delimiter passed as a parameter for the header columns. Wouldn't they usually be the same delimiter as the rest of the file?

Edit: Doh! I remember having thought about this last time. I see what it's doing now. I'm passing in the "headers" via string which is comma delimited. Thanks!

@arodasmedia

This comment has been minimized.

Show comment Hide comment
@arodasmedia

arodasmedia Jun 23, 2017

Hi guys,
I have this result:
Array ( [0] => Array ( [cod_piesa] => gl [ lungime] => 5000 [ latime] => 3000 [ inaltime] => 150 ) [1] => Array ( [cod_piesa] => fd [ lungime] => 3000 [ latime] => 2000 [ inaltime] => 100 ) )

What I would like to do is to insert the above results in a table like this:

$line = 0
$part = GL
$cota = lungime
$value = 5000

then to insert another row in mysql
$line = 0
$part = GL
$cota = latime
$value = 3000

and so on with each line basically I have a component code with different dimensions, instead of inserting in a huge table in mysql I want to add it as a list with while or something.

Thank you very much!

Hi guys,
I have this result:
Array ( [0] => Array ( [cod_piesa] => gl [ lungime] => 5000 [ latime] => 3000 [ inaltime] => 150 ) [1] => Array ( [cod_piesa] => fd [ lungime] => 3000 [ latime] => 2000 [ inaltime] => 100 ) )

What I would like to do is to insert the above results in a table like this:

$line = 0
$part = GL
$cota = lungime
$value = 5000

then to insert another row in mysql
$line = 0
$part = GL
$cota = latime
$value = 3000

and so on with each line basically I have a component code with different dimensions, instead of inserting in a huge table in mysql I want to add it as a list with while or something.

Thank you very much!

@arodasmedia

This comment has been minimized.

Show comment Hide comment
@arodasmedia

arodasmedia Jun 23, 2017

This is what I have in the csv

cod_piesa, lungime, latime, inaltime
gl, 5000, 3000, 150
fd, 3000, 2000, 100

This is what I have in the csv

cod_piesa, lungime, latime, inaltime
gl, 5000, 3000, 150
fd, 3000, 2000, 100

@jeffersongouveia

This comment has been minimized.

Show comment Hide comment
@jeffersongouveia

jeffersongouveia Aug 4, 2017

Thank you very much, saved me a lot of time and probably got better than what I would do.

Thank you very much, saved me a lot of time and probably got better than what I would do.

@KarelWintersky

This comment has been minimized.

Show comment Hide comment
@KarelWintersky

KarelWintersky Sep 20, 2017

A little trick:

$formatter = function($value, $delim = ',', $enclosure = '"', $escape = '\\') use (&$header) {
    if (!$header) {
        $header = array_map('trim', str_getcsv($value, $delim, $enclosure, $escape));
        return $header;
    } else {
        return array_combine($header, array_map('trim', str_getcsv($value, $delim, $enclosure, $escape)));
    }
};

$csv = array_map($formatter, file('data.csv'), array() );

than, first element of array (index 0) will be like this:

  [0]=>
  array(2) {
    [0]=>
    string(4) "name"
    [1]=>
    string(6) "number"
  }

unset($csv[0]); and you will recieve useful two-dimensional array

A little trick:

$formatter = function($value, $delim = ',', $enclosure = '"', $escape = '\\') use (&$header) {
    if (!$header) {
        $header = array_map('trim', str_getcsv($value, $delim, $enclosure, $escape));
        return $header;
    } else {
        return array_combine($header, array_map('trim', str_getcsv($value, $delim, $enclosure, $escape)));
    }
};

$csv = array_map($formatter, file('data.csv'), array() );

than, first element of array (index 0) will be like this:

  [0]=>
  array(2) {
    [0]=>
    string(4) "name"
    [1]=>
    string(6) "number"
  }

unset($csv[0]); and you will recieve useful two-dimensional array

@shyamgarud

This comment has been minimized.

Show comment Hide comment
@shyamgarud

shyamgarud Oct 24, 2017

Thank you vary much!

Thank you vary much!

@OliverLeitner

This comment has been minimized.

Show comment Hide comment
@OliverLeitner

OliverLeitner Jan 23, 2018

thanks alot, this is exaxtly the function i was looking for.

thanks alot, this is exaxtly the function i was looking for.

@debianx

This comment has been minimized.

Show comment Hide comment
@debianx

debianx Mar 18, 2018

Perfect, Thank.

debianx commented Mar 18, 2018

Perfect, Thank.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment