Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display csv file in array

Tags:

I have a .csv file. Some fields are empty and some fields have commas or dots.

Now how I could display it like this in array?

Array (

 [0] => Name1,[email protected],13,56475,,190000,,,remit,5-Mar-15,26250

 [1] => Name2,[email protected],11,11250,,22500,,,the bank,30-Apr-15,6250

 [2] => Name3,[email protected],15,,,1500,receipt,,the market,7-Mar-15,1750

 [3] =>Name4,[email protected],21,25500,,46750,receipt,,bank ,7-Mar-15,21350 ..... )

As of now I can only display it like this:

Array (

 [0] => Name1
 [1] => [email protected]
 [2] => 13
 [3] => 56475
 [4] => 
 [5] => 19000
 [6] => 
 [7] => 
 [8] => remit
 [9] => 5-Mar-15
 [10] => 26250 ) 


Array (
 [0] => Name2
 [1] => [email protected]
 [2] => 11
 [3] => 11250
 [4] => 
 [5] => 22500
 [6] => 
 [7] => 
 [8] => the bank
 [9] => 30-Apr-15
 [10] => 6250 ) ....

And I am using this code:

$file = fopen("pay.csv","r");
while(! feof($file))
{
 echo '<pre>',print_r(fgetcsv($file)),'</pre>';
}
fclose($file);

I prefer using native csv functions.

like image 519
c.k Avatar asked Jun 17 '16 07:06

c.k


2 Answers

If that's your expected output at the top you can simply use file() method to parse the file into an array.

$lines = file('file.csv');

foreach ($lines as $line_num => $line) {
 echo $line . '<br />';
}
like image 163
Farkie Avatar answered Sep 28 '22 04:09

Farkie


fgetcsv() can solve your problem..

The fgetcsv() function parses a line from an open file, checking for CSV fields.

  • The fgetcsv() function stops returning on a new line, at the specified length, or at EOF, whichever comes first.

  • This function returns the CSV fields in an array on success, or FALSE on failure and EOF.

Syntax

fgetcsv(file,length,separator,enclosure)

  • file Required. Specifies the file to check.
  • length : Specifies the maximum length of a line. Must be greater than the longest line (in characters) in the CSV file. Omitting this parameter (or setting it to 0) the line length is not limited, which is slightly slower.

Example:

<?php
$file = fopen("contacts.csv","r");
print_r(fgetcsv($file));
fclose($file);
?>

The CSV file:

Kai Jim, Refsnes, Stavanger, Norway
Hege, Refsnes, Stavanger, Norway

The output of the code above will be:

Array
(
[0] => Kai Jim
[1] => Refsnes
[2] => Stavanger
[3] => Norway
)

Visit http://php.net/manual/en/function.fgetcsv.php for more reference.

like image 29
Tirthraj Rao Avatar answered Sep 28 '22 02:09

Tirthraj Rao