I am trying to build a service called DataFileParser
in my Symfony application which reads a csv file. I changed the parse
function of my service for the purpose of this question, to make it look more simple: in my code snippets, my function just loops through the lines of the csv file and dumps them.
My DataFileParser
looks like this:
class DataFileParser
{
/**
* @param string $filename
* @param array $expectedColumns
*
* @return EntryIterator
*/
public function parse($filename, $requiredColumns, $expectedColumns)
{
$splFileObject = new \SplFileObject($filename, 'r');
$splFileObject->setFlags(\SplFileObject::READ_CSV);
$splFileObject->setCsvControl(';');
foreach ($splFileObject as $line) {
var_dump($line);
}
die;
}
}
My csv file looks like this:
firstname;lastname;mail
john;small;jonh.small@fakemail.com
My parse function output looks like this:
array(5) {
[0]=> string(9) "firstname"
[1]=> string(8) "lastname"
[2]=> string(9) "mail john"
[3]=> string(5) "small"
[4]=> string(23) "jonh.small@fakemail.com"
}
As you can see on the index #2, the SplFileObject does not detect the end of line between the last header "mail" and the "john" string, as it prints [2]=> string(9) "mail john"
whereas I would have expected the following
[2]=> string(4) "mail"
[2]=> string(4) "john"
If I use the dump function of the var_dumper
component of Symfony instead of var_dump
, I get this
array:5 [▼
0 => "firstname"
1 => "lastname"
2 => "mail\rjohn"
3 => "small"
4 => "jonh.small@fakemail.com"
]
As you can see, the SplFileObject does not detect the \r
as the end of the first line.
If I manually set the PHP parameter 'auto_detect_line_endings'
to true by calling ini_set('auto_detect_line_endings',true);
before the SplFileObject constructor, then it works fine and I get the following output (correct one) with the dump function.
array:3 [▼
0 => "firstname"
1 => "lastname"
2 => "mail"
]
array:3 [▼
0 => "john"
1 => "small"
2 => "jonh.small@fakemail.com"
]
Last details, the $filename
parameter of my parse function is an instance of the class Symfony\Component\HttpFoundation\File\UploadedFile
. My operating system is Mac OS X El Capitan, I am using MAMP with PHP version 7.1.8 and I am using PhpStorm to edit the CSV file (I checked my PhpStorm config for coding style and have already set \n
as the line separator).
Now my question is:
How can I set the SPLFileObject to detect the \r
as a line break without having to change the PHP variable auto_detect_line_endings
? As well as detecting all types of line breaks (\r
, \n
, \n\r
) through all operating systems as line breaks?
(P.S.: Maybe it is an issue with my PhpStorm editor since I cannot figure out how to insert a \n
with the enter key. So if anybody knows why my PhpStorm does not insert \n
instead \r
even though I have defined \n
as the line separator, I would be glad to share knowledge).
Screenshot of PHPStorm Configuration of Line break: