Leggere i contenuti di un file CSV con PHP

Leggere i contenuti di un file CSV con PHP

In PHP è relativamente semplice effettuare il parsing di un file CSV.

La soluzione è la seguente:


function parse_csv_file($path) {
    $full_path = $_SERVER['DOCUMENT_ROOT'] . $path;
    $contents = [];

    if(!file_exists($full_path) || !is_readable($full_path)) {
        return $contents;
    }

    if(mime_content_type($full_path) !== 'text/csv') {
        return $contents;
    }

    $file = fopen($full_path, 'r');
    $headers = fgetcsv($file);
    

    while (($data = fgetcsv($file)) !== false) {
        if (count($data) == 1 && is_null($data[0])) {
            continue;
        }
        $contents[] = array_combine($headers, $data);
    } 
    fclose($file);
    return $contents;   
}

Esempio d'uso:


<?php
print_r(parse_csv_file('/data/test.csv'));

Torna su