The Trouble With (Line) Endings

PHP Hypertext Preprocessing
Jul
1

In PHP it's probably quite common to want to import data into your database using a CSV file, or an XML file - even though phpMyAdmin is capable of doing it. As I recently found out though, this can sometimes be an issue in itself. In this particular example there was a CSV file from an unknown system that was being read in by PHP and processed but it appeared like it was only reading in the first line due to way the data was being processed. As it turned out the entire file was being read in as a single line, and since the script was using fgetcsv to read in a line of comma separated variables it turned out to be pretty obvious what was happening after using print_r on the output.

I knew that fgetcsv didn't have a parameter for specifying a line ending character so I decided to investigate what could be done to solve the problem. Eventually I found:

<?php
   ini_set('auto_detect_line_endings', true);
?>

After putting that line in before reading in the file all the problems were solved and the file was read in correctly. A strange issue, but a simple solution.

your comments - Post a comment

Hunter

Is that line in the phpmyadmin config or is that in the source? It seems like it might be in the source from context but wanted to be sure... any hint on what file/line?

Hunter commented 4 years ago
David G. Paul

I'm not sure if or where the line exists in phpMyAdmin - though I believe they may actually tackle the problem a different way. The PHP function mentioned in the post was intended for pretty much any script, but could actually be done via the php.ini file if you have access to it.

David G. Paul commented 4 years ago
blog comments powered by Disqus