01 November, 2010

CSV to Multi-Dimensional Array in PHP

Once i needed to convert a csv file contents to a multi-dimensional array in php. Converting a csv to a multi-dimensional array
can be done by reading the file by using php's fopen function and then looping through to insert data to the array.
Following is a code snippet that is used to get csv to multi-dimensional array in php.
My csv file was in the format "name" "email_address" without any column names.

$formattedArr = array();
$filename = "test.csv";
//csv format was
//name test@this.com
//tester tester@mail.com
//sudhir sudhirconscious@gmail.com
if (($handle = fopen($filename, "r")) !== FALSE) {
$key = 0; // Set the array key.
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$count = count($data); //get the total keys in row
//insert data to our array
for ($i=0; $i < $count; $i++) {
$formattedArr[$key][$i] = $data[$i];
fclose($handle); //close file handle
//csv to multidimensional array in php
echo "
echo "
And thats it.

1 comment:

Anonymous said...

Emails on Csv File save into database It workes fine for me Nice one. Sudhir keep ir up