Ami Kamboj
Ami Kamboj

Reputation: 105

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
)

Upvotes: 0

Views: 8666

Answers (4)

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];
      }

Upvotes: 0

Martin Tonev
Martin Tonev

Reputation: 775

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 

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

Upvotes: 1

chresse
chresse

Reputation: 5805

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.

Upvotes: 3

Fluffeh
Fluffeh

Reputation: 33502

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);
    }
?>

Upvotes: 2

Related Questions