chouaib23
chouaib23

Reputation: 481

PHP read CSV file line by lines

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

Upvotes: 35

Views: 73539

Answers (2)

Sofiene Djebali
Sofiene Djebali

Reputation: 4508

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);

Upvotes: 75

Surendra Suthar
Surendra Suthar

Reputation: 370

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];
              }
            }
    }

Upvotes: 2

Related Questions