I need to upload a CSV file that includes comma-separated numbers.
Is there any way not to let it interpret a tab as CSV separator? Or I have to use a TSV file?
I need to upload a CSV file that includes comma-separated numbers.
Is there any way not to let it interpret a tab as CSV separator? Or I have to use a TSV file?
You can change a variety of settings when using the fgetcsv function:
fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]]] )
You can set the delimiter to any character that you want (space, tab, pipe, etc).
The enclosure is for if you need to include content that would normally break the file format (e.g. having a comma within the content when a comma is used as a delimiter). The default is a double quote. For instance:
id, name
1, Ted Mend
2, Tracy Gale
4, John Dee, Jr
Line with ID 4 would break the file since there is a comma in the name, but wrapping it with the enlosure character tells the parser to ignore the breaking characters within. The following would be valid and the comma before Jr would not cause an error or misread lines:
id, name
1, "Ted Mend"
2, "Tracy Gale"
4, "John Dee, Jr"
The final argument, the escape character, is used if you still need to utilize it within the enclosed string (e.g. a double quote within the double quoted content). You can place the escape character before any double quote character within the double-quoted content to ensure it does not break the format:
id, title, type
1, "Up", "movie"
2, "Gone with the Wind", "movie"
3, "\"The Witcher 3\"", "video-game"
Notice there is a backslash prior to the double quotes within the video game title. This allows the parser to know that the double quotes around the title are expected to be part of the title string and not an end to the column's content.