0

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
)
Ami Kamboj
  • 105
  • 1
  • 10

4 Answers4

3

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.

chresse
  • 5,486
  • 3
  • 30
  • 47
2

You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this:

<?php
    $handle = @fopen("/tmp/inputfile.txt", "r");
    if ($handle) 
    {
        while (($buffer = fgets($handle)) !== false) 
        {
            $array=explode(",",$buffer);
            print_r($array)
            // You have your array at this point.
        }
        if (!feof($handle)) 
        {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
    }
?>
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
  • okay thankyou , this will fine if i got the array like column wise. like id column has a different array corresponding key having name as different array. – Ami Kamboj May 31 '14 at 10:50
  • I'm sorry, I don't understand what you are asking. Can you edit your question to add in what you mean? – Fluffeh May 31 '14 at 10:56
  • Okay please check the question again i am going to make two different array. I hope you clear what i need. – Ami Kamboj May 31 '14 at 10:58
1

Without one unnecessary for cicle :

$handle = fopen($name, "r");

    $first_row = true;
    $final_ata = array();
    $headers = array();

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {           
        if($first_row) {
            $headers = $data;
            $first_row = false;
        } else {
            $final_ata[] = array_combine($headers, array_values($data));
        }
    }

    echo '<pre>';
    print_r($final_ata);die;

will give you result:

Array
(
[0] => Array
    (
        [column1] => value
        [column2] => value
        [column3] => value
    )

[1] => Array
    (
        [column1] => value
        [column2] => value
        [column3] => value
    )

[2] => Array 

..............

Martin Tonev
  • 747
  • 12
  • 21
0

This is a comma-separated value not exactly column-wise. If you have a comma in column value so it will also break your string.

$file = $_FILES['file']['tmp_name']; $handle = fopen($file, "r");

      while(($filesop = fgetcsv($handle, 100000, ",")) !== false){
       $abc= $filesop[0];
       $xyz= $filesop[1];
      }