Harendra Singh
Harendra Singh

Reputation: 203

How to read .csv file row wise using PHP

I am trying to make a PHP script that reads each row of a .csv file. I want to treat each row as an array of data. Please suggest how I can achieve the above?

enter image description here

Upvotes: 1

Views: 3656

Answers (4)

Mistery
Mistery

Reputation: 43

You can use the fgetcsv function to read data from a csv file. Please, look at this : http://php.net/manual/en/function.fgetcsv.php

Upvotes: 0

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21691

You can use following to read row from csv file and create array from the csv file:

<?php
$file = fopen("/path/to/file.csv","r");
$arrayCsv = array();
while(!feof($file)) {      
  $fpTotal = fgetcsv($file);
  array_push($arrayCsv,$fpTotal);
}
fclose($file);
print_r($arrayCsv); //prints array from csv
?>

Upvotes: 0

Al Foиce    ѫ
Al Foиce ѫ

Reputation: 4315

Use the function fgetcsv().

// Read the first line, headers
$headers = fgetcsv($file);
// Now $headers is an array of your headers

// Read the lines one by one
while (false != ($line = fgetcsv($file))) {
    // $line is an array of your cells
}

Upvotes: 2

atoms
atoms

Reputation: 3093

You could use the following to create an array from the csv;

$aArray = str_getcsv ( file_get_contents("/path/to/file.csv") , ',', '"', "\\");
var_dump($aArray);

Have a read of the PHP manual; str_getcsv() and file_get_contents()

Upvotes: 1

Related Questions