<?php
ini_set('auto_detect_line_endings', TRUE);
$csv = array_map('str_getcsv', file('Testcsv.csv'));
print_r($csv);
This code parses the Testcsv.csv file that looks like this..
4,5,6,7,8
9,10,11,12,13
0,1,3,2,15
However the last print statement returns
Array
(
[0] => Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 7
[4] => 8
)
[1] => Array
(
[0] => 9
[1] => 10
[2] => 11
[3] => 12
[4] => 13
)
[2] => Array
(
[0] => 0
[1] => 1
[2] => 3
[3] => 2
[4] => 15
)
)
vardump($csv) produces
array(3) {
[0]=>
array(5) {
[0]=>
string(4) " 4"
[1]=>
string(1) "5"
[2]=>
string(1) "6"
[3]=>
string(1) "7"
[4]=>
string(1) "8"
}
[1]=>
array(5) {
[0]=>
string(1) "9"
[1]=>
string(2) "10"
[2]=>
string(2) "11"
[3]=>
string(2) "12"
[4]=>
string(2) "13"
}
[2]=>
array(5) {
[0]=>
string(1) "0"
[1]=>
string(1) "1"
[2]=>
string(1) "3"
[3]=>
string(1) "2"
[4]=>
string(2) "15"
}
}
No matter what I do or how I format the csv, the first value always gets an empty space pushed in front of it. In this case, " 4" instead of "4". I can't understand why. I am on a mac computer, and without the first line of code things get really wonky as it doesn't detect the line breaks. I created and saved the .csv in Excel. Any insight helps, thanks.
My guess is that your file actually has that character, or a hidden character in front of it.
To find out what it, open your terminal. If the file is called 'foo.csv', use:
hexdump -C foo.csv
This will give you a hexdump of your file. I'm almost certain that you find a hidden character before the first 4.
edit thanks for posting the hexdump. Your file contains a UTF-8 BOM. Either make sure that whatever creates the file does not output the UTF-8 BOM, or clean up the file before you open it.
Writing a UTF-8 BOM is mostly no longer done by modern software. I don't think it's recommended anymore but some software might still do this.