Skip to content

Instantly share code, notes, and snippets.

@marcanuy
Last active April 6, 2024 17:07
Show Gist options
  • Save marcanuy/ae7a2d0ab167e8e616f3 to your computer and use it in GitHub Desktop.
Save marcanuy/ae7a2d0ab167e8e616f3 to your computer and use it in GitHub Desktop.
Iterate through lines in an external file with PHP
<?php
$file = new SplFileObject("animals.csv");
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
list($animal, $class, $legs) = $row;
printf("A %s is a %s with %d legs\n", $animal, $class, $legs);
}
?>
#Contents of animals.csv
crocodile,reptile,4
dolphin,mammal,0
duck,bird,2
koala,mammal,4
salmon,fish,0
#The above example will output something similar to:
A crocodile is a reptile with 4 legs
A dolphin is a mammal with 0 legs
A duck is a bird with 2 legs
A koala is a mammal with 4 legs
A salmon is a fish with 0 legs
$filename = 'myfile.csv';
$file = new SplFileObject($filename);
while (!$file->eof()){
$line = $file->current();
$file->next();
}
@lateagain
Copy link

while (!$file->eof()) repeats the last line because you don't see the eof until the read.
while($line = $file->current()) works better. It combines the read and the test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment