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.
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 />';
}
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With