0

I'm trying to parse a CSV file and read its contents. I get file like this:

$lines = file(base_path() . '/storage/data/test.csv', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

After that, I use dd($lines) to get its output and it's like this:

array:4 [
  0 => "Column1,Column2,Column3"
  1 => "row11,row12,row13"
  2 => "row21,row22,row23"
  3 => "row31,row32,row33"
]

Which is okay so far. I'm exploding every line.

$check = 'Column1';
foreach ($lines as $line) {
    $exploded = explode(',', $line);
    if (($index = array_search($check, $exploded)) !== false) {
        echo $index;
    }
}

I can get every index of that $exploded array for matching value. Except "Column1", A1 value. I've also checked that after the first explode function:

dd(trim($exploded[0]) === trim($check))

It's printing "false". But I've printed them both, and they are both "Column1". Is there anything I'm missing?

  • Use something to show the actual string length(something like `var_dump()`), it may be that there is a byte order mark (BOM) on the start of the file. – Nigel Ren Apr 14 '20 at 08:25
  • @NigelRen like you said, I've checked with var_dump. Length of $exploded[0] is 13 and length of $check is 10. I've trimmed $exploded[0] and still 13. What could have been the problem? – Oğuz Öztınaz Apr 14 '20 at 08:36
  • 1
    Try https://stackoverflow.com/questions/10290849/how-to-remove-multiple-utf-8-bom-sequences – Nigel Ren Apr 14 '20 at 08:37
  • FYI: I would change `base_path() . '/storage/data/test.csv'` into `base_path('storage/data/test.csv')` or even better: `storage_path('data/test.csv')`. It is not part of the issue, but please use functions as they are intended :D – Techno Apr 14 '20 at 09:19
  • @RobBiermann I've appreciated for your comment. I'll make those changes and keep them in mind for further :) – Oğuz Öztınaz Apr 14 '20 at 11:45

0 Answers0