Parse an uploaded CSV file in 2 lines in PHP/CakePHP

Nasty but gets it done:

$delim = ','; $enc = '"'; $line = "\n";
foreach( str_getcsv ( file_get_contents( $tmpname ), $line ) as $row ) $csv[] = str_getcsv( $row, $delim, $enc ); // print_r( $csv );

or, if you want to be even more crazy, in 1 (note, config options are inline but I left the assignments so they are findable):

foreach( str_getcsv ( file_get_contents( $tmpname ), $line = "\n" ) as $row ) $csv[] = str_getcsv( $row, $delim = ',', $enc = '"' ); // print_r( $csv );

or, if you want it to be one expression, but more readable:

foreach( 
	str_getcsv ( file_get_contents( $tmpname ), $line = "\n" ) 
	as 
	$row ) 
		$csv[] = str_getcsv( $row, $delim = ',', $enc = '"' ); 
		
// print_r( $csv );

In the examples above, I’m assuming you already know the temporary name of the uploaded file. In regular PHP, you could prepend this code with

$tmpname = $_FILES[0][tmp_name];

In CakePHP, you might just replace $tmpname with $this->data[‘Whatever’][‘csv’][‘tmp_name’];
This kind of assumes you had done something like this on the form page:

echo $this->Form->create('Whatever', array('type' => 'file'));
echo $this->Form->file('csv');
echo $this->Form->end('upload');

Leave a Comment

Your email address will not be published. Required fields are marked *