PHP: salvare i dati di un file CSV in un array

PHP:  salvare i dati di un file CSV in un array

In PHP è relativamente semplice salvare i dati di un file CSV in un array.

La soluzione è la seguente:


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

    if(!file_exists($full_path) || !is_readable($full_path)) {
        error_log("$full_path cannot be read.", 0);
        return $contents;
    }

    $type = mime_content_type($full_path);
    if($type !== 'text/csv') {
        error_log("$full_path is not a CSV file.", 0);
        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:


print_r(parse_csv_file('/data/test.csv'));

Torna su