Skip to content

Instantly share code, notes, and snippets.

@jaywilliams
Created April 30, 2010 23:18
Show Gist options
  • Save jaywilliams/385876 to your computer and use it in GitHub Desktop.
Save jaywilliams/385876 to your computer and use it in GitHub Desktop.
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
)
)
@zhanls
Copy link

zhanls commented Jul 1, 2018

Thanks for the function, it works like a charm.

@virenbpanchal
Copy link

Thanks you very much. I was looking for a solution about to insert CSV file data which contains comma(,) in most of the columns values. I used Csvreader library but by using that I got data by exploding from comma(,) in column value. Now I got your function csv_to_array() and it solved my problem.

@hAbd0u
Copy link

hAbd0u commented Jul 16, 2019

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

This happen because your csv file has special encoding, first you need to know what is it, than remove it. In my case was UTF-BOM, so the final version would be like this:

function csv_to_array($filename='', $delimiter=',', $encoding = NULL)
{
	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)
				if($encoding) {
					$header = preg_replace('/' . $encoding . '/', '', $row); 
				}
				else
					$header = $row;
			else
				$data[] = array_combine($header, $row);
		}
		fclose($handle);
	}
	return $data;
}

Example:

print_r(csv_to_array('example.csv',,'[\x80-\xFF]')); // This will remove UTF-8 encoding
print_r(csv_to_array('example.csv', ',','[\x80-\xFF]')); 

@despe4er
Copy link

Thanks!

@mlpassos
Copy link

I have tried something like 3 different libraries for codeigniter with no success. Yours is the first one that works perfect without a touch.

THANK YOU!

@Djsteiner79
Copy link

Djsteiner79 commented Apr 23, 2020

Hi Thanks for the script :)

I will like to know how to make a foreach loop through the array? because I will like to echo the result out in a table

@jaywilliams
Copy link
Author

Sure, here's a simple, primitive example (code untested):

<?php
$data = csv_to_array('example.csv');

echo "<table>";
foreach ($data as $row) {
    echo "<tr>";
    foreach ($row as $column) {
        echo "<td>$column</td>";
    }
    echo "</tr>";
}
echo "</table>";

@Djsteiner79
Copy link

Thank you so much. 😊👍

@Djsteiner79
Copy link

Hi agaín :)

In the csv file there are two columns ,name and numbers, I will like do use the PHP max() Function to get the highest value in an array of the cummum number?

How can i do that?

@jaywilliams
Copy link
Author

There's many ways you can achieve that, I'd suggest reading through this tutorial, or picking up a good book on the PHP language. With a little time, it's easy to pick up the basics.

@Djsteiner79
Copy link

Thanks I do know some basic PHP and i have made this task, justmore simple, without the csv file, but this is a little more advanced for me :)

<style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; }

td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
</style>


"; echo "Det lavest Tempartur er: ". (min($temp_array)). "°

"; echo " "; $Mtemp = array( "78, 60, 62, 68, 71, 68, 73, 85, 66, 64, 76, 63, 81, 76, 73, 68, 72, 73, 75, 65, 74, 63, 67, 65, 64, 68, 73, 75, 79, 73, 45"); $datesOFM = array('01-01-2011, 02-01-2011, 03-01-2011, 04-01-2011, 05-01-2011, 06-01-2011, 07-01-2011, 08-01-2011, 09-01-2011, 10-01-2011,11-01-2011, 12-01-2011, 13-01-2011, 14-01-2011, 15-01-2011,16-01-2011, 17-01-2011, 18-01-2011, 19-01-2011, 20-01-2011, 21-01-2011, 22-01-2011, 23-01-2011, 24-01-2011, 25-01-2011, 26-01-2011, 27-01-2011, 28-01-2011, 29-01-2011, 30-01-2011, 31-01-2011'); echo " "; foreach($Mtemp as $key => $value) { echo "" . ""; } echo "
Dato Tempertur
" . $datesOFM[$key] . " " . $Mtemp[$key] . "
"; ?>

@Octagon-simon
Copy link

Thanks @rboatright

@MKaidan
Copy link

MKaidan commented Mar 3, 2023

As of PHP 8.0, you can set the length to 0 (or null, or omit it entirely) for the fgetcsv() function if you don't want to limit the maximum line length.

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