PHPRO.ORG

Verify CSV File Is Valid CSV Format

Verify CSV File Is Valid CSV Format

Whilst a CSV file has format, the exact format of each line is unknown, and verifying if a file is in CSV format is almost impossible.

Both of the below formats are perfectly valid for an CSV parser, such as str_getscv.

one,two
one,"two",three
one
tow

Perhaps the best that can be hoped for, is defining what makes a file not a CSV file. Basically, if it does not match one of the MIME types that a CSV file could possibly be.


<?php

public function isCSV$file )
{
    
$csv_mime_types = [ 
        
'text/csv',
        
'text/plain',
        
'application/csv',
        
'text/comma-separated-values',
        
'application/excel',
        
'application/vnd.ms-excel',
        
'application/vnd.msexcel',
        
'text/anytext',
        
'application/octet-stream',
        
'application/txt',
    ];
    
$finfo finfo_openFILEINFO_MIME_TYPE );
    
$mime_type finfo_file$finfo$file );

    return 
in_array$mime_type$csv_mime_types );
}

?>

Usage


<?php

$file 
"my_file.csv";
if( 
isCSV$file )
{
    echo 
"This is a CSV file";
}
else
{
    echo 
"This is not a CSV file";
}
?>