Search code examples
phpcsvfgetcsv

read the csv file column wise


I want to read the csv file column wise and get the every column data into specified array

this will contains a numbers of column

[country]
Array(
[0]=>Australia
)
[city]
Array(
[0]=>vic
)

Solution

  • you can use the fgetcsv function:

    if (($handle = fopen("inputfile.csv", "r")) !== false) {
        $filesize = filesize("inputfile.csv");
        $firstRow = true;
        $aData = array();
        while (($data = fgetcsv($handle, $filesize, ";")) !== false) {
            if($firstRow) {
                $aData = $data;
                $firstRow = false;
            } else {
                for($i = 0;$i < count($data); $i++) {
                    $aData[$i][] = $data[$i];
                }
            }
        }
        fclose($handle);
    }
    

    so you will get an multidimensional array with first row of headers.