Question

I have a CSV file like the following (it has approx 500 rows)

ID,Title,LastName,HouseNo,Street,City,Postcode,Telephone
1209109,Miss,Test,1635,Test Road,Test, AB12 2EF,
1209833,Mrs,Test,3,Test Close,Test,BB12 2EF,
1205839,Miss,Test,1,Test Road,Test,AA12 2EX,

I am then using the following PHP:

$handle = fopen($csvFile, "r");
$imports = array();

$row = 1;
echo "<table>";
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
{
       // skip headers
       if($row == 1){ $row++; continue; }
       echo "<tr>";
       echo "<td>$data[0]</td>";
       echo "<td>$data[1]</td>";
       echo "<tr>";

} 
echo "</table>";
fclose($handle);`

I expect something like:

1209109   Miss
1209833   Mrs

But for some reason, it seems to start at a random point in the file and then output some of the data in the wrong <td>.

Could the provlem be the trailing comma on each line?

Thanks

Was it helpful?

Solution

I'm guessing that the issue you're having is an End of Line (EOL) mismatch. Basically, the fgetcsv() function breaks up a file based on a new-line character, but it's expecting a different character than the one that's being using the file (for instance, \n\r vs \r vs \n). The result is that the function is just grabbing the first 1000 characters (as per the function call) and treating it as the first line, then it's grabbing the next 1000 character, etc... this would result in somewhat random outputs.

You might be able to try something like:

ini_set('auto_detect_line_endings', true);

before you grab the file. Or you could go through and manually modify the CSV to standardize the EOL characters/open the spreadsheet in a file-conversion which allows you to change the EOL character (i.e. Unix vs Windows

OTHER TIPS

I haven't been able to reproduce your error with the data you've provided (even with the trailing comma left on or removed), but I did notice that you're not closing out your table row in the code you've supplied.

I don't think this would be contributing to your display error, but you may want to change your code to be:

$row = 1;
echo "<table>";
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
{
   // skip headers
   if($row == 1) {
     $row++; 
     continue; 
   }
   echo "<tr>";
   echo "<td>$data[0]</td>";
   echo "<td>$data[1]</td>";
   echo "</tr>\n";

} 
echo "</table>";
fclose($handle);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top