How to make an array from csv in php

Author:Kostas Sp Published On:September 19, 2014 Under:Php

 
 

This is a tutorial that demostrates how from a csv we can create an array in php.
 
arrays-php
 

How to Convert a comma separated file into an associated array.

 
<?php
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;
}
 
/**
 * Example
 */
 
print_r(csv_to_array('example.csv'));

 
The example.csv must be of this form
 

"name", "age","gender","gender2"
"kostas", 11, male , robot
"nikole", 22, female , human

 
And the output on your web server should be exactly like below.
 

Array ( [0] => Array ( [name] => kostas [age] => 11 [gender] => male [gender2] => robot ) [1] => Array ( [name] => nikole [age] => 22 [gender] => female [gender2] => human ) )
   
Tags:
 

Leave a Reply


8 − = five

.
 
Categories
TEST

Anything in here will be replaced on browsers that support the canvas element

Tags