Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP read CSV file line by lines

Tags:

php

csv

I have a CSV file loaded from an URL, and I want to loop over the lines with PHP.

Here is a typical line of this CSV:

1004000018;active;"TEST1";"TEST2";"TEST3";"TEST4"  

I would like to get this result, for each row:

1004000018 active TEST1 TEST2 TEST3 TEST4 
like image 312
chouaib23 Avatar asked May 21 '16 10:05

chouaib23


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)) !==

What does Fgetcsv do in php?

PHP - Function fgetcsv() The fgetcsv() function can parse a line from an open file and check for CSV fields. This function stops returning on a new line at a specified length or EOF, whichever comes first. This function returns CSV fields in the array on success or false on failure and EOF.


2 Answers

You can achieve this using the php function fgetcsv, this should work :

PHP

$file = fopen('file.csv', 'r'); while (($line = fgetcsv($file)) !== FALSE) {    //$line[0] = '1004000018' in first iteration    print_r($line); } fclose($file); 
like image 105
Sofiene Djebali Avatar answered Sep 18 '22 12:09

Sofiene Djebali


This will help you for read csv:

   if (($handle = fopen("$source_file", "r")) !== FALSE) {         $columns = fgetcsv($handle, $max_line_length, $delemietr);         if (!$columns) {             $error['message'] = 'Empty';              return ($error);         }          while (($rows = fgetcsv($handle, 10000, "\t")) !== false) {             if ($rows[1] && array(null) !== $rows) { // ignore blank lines                         $data1 = $rows[1];               }             }     } 
like image 21
Surendra Suthar Avatar answered Sep 18 '22 12:09

Surendra Suthar