Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract data from csv file in PHP

Tags:

php

split

csv

I have a csv file which looks like this

$lines[0] = "text, with commas", "another text", 123, "text",5; $lines[1] = "some without commas", "another text", 123, "text"; $lines[2] = "some text with commas or no",, 123, "text"; 

And I would like to have a table:

$t[0] = array("text, with commas", "another text", "123", "text","5"); $t[1] = array("some without commas", "another text", "123", "text"); $t[2] = array("some text, with comma,s or no", NULL , "123", "text"); 

If I use split($lines[0],",") I'll get "text" ,"with commas" ... Is there any elegant way to do it?

like image 430
liysd Avatar asked May 10 '10 18:05

liysd


People also ask

How do I retrieve data from a CSV file?

Step 1) To read data from CSV files, you must use the reader function to generate a reader object. The reader function is developed to take each row of the file and make a list of all columns. Then, you have to choose the column you want the variable data for.

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 display the content of a CSV file in HTML?

To display the data from CSV file to web browser, we will use fgetcsv() function. Comma Separated Value (CSV) is a text file containing data contents. It is a comma-separated value file with . csv extension, which allows data to be saved in a tabular format.


2 Answers

You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.

Example from PHP Manual:

$row = 1; if (($handle = fopen("test.csv", "r")) !== FALSE) {     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {         $num = count($data);         echo "<p> $num fields in line $row: <br /></p>\n";         $row++;         for ($c=0; $c < $num; $c++) {             echo $data[$c] . "<br />\n";         }     }     fclose($handle); } 
like image 193
Matt Avatar answered Sep 24 '22 06:09

Matt


In addition to Matt's suggestion, you can also use SplFileObject to read in the file:

$file = new SplFileObject("data.csv"); $file->setFlags(SplFileObject::READ_CSV); $file->setCsvControl(',', '"', '\\'); // this is the default anyway though foreach ($file as $row) {     list ($fruit, $quantity) = $row;     // Do something with values } 

source: http://de.php.net/manual/en/splfileobject.setcsvcontrol.php

like image 28
Gordon Avatar answered Sep 21 '22 06:09

Gordon