jrobinsonc
5/3/2017 - 1:03 PM

Read files in PHP no matter line endings.

Read files in PHP no matter line endings.

<?php

ini_set('auto_detect_line_endings', true);

$states_list = [];
$handle = @fopen('states-list.csv', 'r');

if ($handle !== false) {

    while (!feof($handle)) {
        $buffer = fgets($handle);

        if (preg_match('#^(.+),([A-Z]{2})$#', trim($buffer), $matches) === 1) {
            $states_list[$matches[2]][] = trim($matches[1], '"');
        }
    }

    fclose($handle);
}