I am trying to read data from a comma separated text file called test.txt using PHP. The file contents is as follows:
Sel,10,5,4
Tati,5,6,7
Vinny,10,10,10
I tried to read these values using a loop with fgets(), which is used to print line by line and fgets() and explode(), which are supposed to write element per element in each line.
<?php
$file=fopen('test.txt','r');
if(!$file)
{
echo "Error reading file";
die;
}
echo"Reading Line by Line";
while(!feof($file))
{
$pointer=fgets($file,4096);
echo "<p>".$pointer."<p>";
}
rewind($file);
echo "Reading value by value per line";
while(!feof($file))
{
$pointer=fgets($file,4096);
$pieces = explode(",", $pointer);
echo"<hr>";
echo "<p> Name:".$pieces[0]."<p>";
echo "<p> Grade 1:".$pieces[1]."<p>";
echo "<p> Grade 2:".$pieces[2]."<p>";
echo "<p> Grade 3:".$pieces[3]."<p>";
echo"<hr>";
}
fclose($file);
?>
However, when I use fgets() and explode() functions in php there is a line printed with no values. This is strange, as I have only three lines in my text file and when I use fgets() without explode() it returns the values in the correct number of lines.
What is wrong in this code?
Edit: here is my code