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?
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.
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)) !==
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.
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); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With