I have some code to display CSV file data in PHP. Out of these code is something like this
row1
row2
row3
row4
BLANK(this is not any data)
<?php
$csvFile = 'abc.csv';
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) )
{
$csv_data[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
foreach($csv_data as $data)
{
echo "column 2 = ".$data[1]; echo "<br>";
}
?>
expected output :
row1
row2
row3
row4
i have only these four rows but it prints 5 with last blank rows. Please suggest me the best solution. Thanks.
You could try this:-
<?php
$csvFile = 'abc.csv';
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) )
{
$csv_data[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
$csv_data = array_pop($csv_data); // delete last element of Array
foreach($csv_data as $data)
{
echo "column 2 = ".$data[1]; echo "<br>";
}
?>
you are appending <br/>
at the end so it will print blank line at the last as well try this code
$count = 0;
foreach($csv_data as $data)
{
if($count>0)
{
echo "<br>";
}
echo "column 2 = ".$data[1];
$count+=1;
}
I got this solution by adding this code
if (empty($data)) {
break;
}
This is the whole code of my script
<?php
$csvFile = 'abc.csv';
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) )
{
$csv_data[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
foreach($csv_data as $data)
{
if (empty($data)) {
break;
}
echo "column 2 = ".$data[1]; echo "<br>";
}
?>