36

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
1
  • 1
    So look at using the fgetcsv() function with a ; separator Commented May 21, 2016 at 10:44

2 Answers 2

76

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Why don't you use fgetcsv() instead of explode().... one less operation, a function designed specifically to handle the other subtle nuances of CSV (such as quoted strings, and the separator appearing inside an actual value)
@chouaib23 i edited the post using fgetcsv, now you can access the variable $line as an array, for instance : $line[0] in the first iteration will be equal to $line[0] = '1004000018';
Thanks Problem Solved
In order to get an array, you need delimiter of ";" passed to the fgetcsv, in the example above.
Does this line $file = fopen('file.csv', 'r'); load the entire file into memory?
|
2

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

2 Comments

Hello there is porblem my csv has multi line and i want get only last line in fille
Then you need to add nested loop to get total lines & get last row data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.