Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload and parse a CSV file in php

Tags:

php

csv

I want to upload a csv file with php. After the file is uploaded, I want to display the data of the CSV file. I would like an example how to accomplish this task.

like image 855
n92 Avatar asked Apr 08 '11 10:04

n92


People also ask

How do I read a csv file in column wise in php?

You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==

How do I create a CSV file and download a php script?

$fh = fopen('somefile. csv', 'w') or die('Cannot open the file'); for( $i=0; $i<count($arr); $i++ ){ $str = implode( ',', $arr[$i] ); fwrite( $fh, $str ); fwrite( $fh, "\n" ); } fclose($fh);


1 Answers

This can be done in a much simpler manner now.

$tmpName = $_FILES['csv']['tmp_name']; $csvAsArray = array_map('str_getcsv', file($tmpName)); 

This will return you a parsed array of your CSV data. Then you can just loop through it using a foreach statement.

like image 163
Thomas Clowes Avatar answered Oct 02 '22 17:10

Thomas Clowes