Converting CSV to PHP Array - issue with end line (CR LF)

前端 未结 2 1299
孤城傲影
孤城傲影 2021-01-19 08:58

I am converting csv file to an array using code bellow. But, problem is that end of the row is CR LF, and it is not detected, so array has wrong offset. CR

相关标签:
2条回答
  • 2021-01-19 09:20

    Have you tried using fgetcsv()? full info on php.net.

    Example usage from php.net

    <?php
    $row = 1;
    if (($handle = fopen("test.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>\n";
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo $data[$c] . "<br />\n";
            }
        }
        fclose($handle);
    }
    ?>
    
    0 讨论(0)
  • 2021-01-19 09:32

    I would avoid str_getcsv() and work with fgetcsv() to avoid dealing with some of the end of line futz.

    http://php.net/manual/en/function.fgetcsv.php

    if (($handle = fopen("fileName", "r")) !== FALSE) {
        while (($data = fgetcsv($handle)) !== FALSE) {
          var_dump($data);  //array representation of one line of csv...
        }
    }
    fclose($handle);
    

    If you're on a Mac...

    Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

    0 讨论(0)
提交回复
热议问题