loop though text file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
inosent1
Forum Commoner
Posts: 97
Joined: Wed Jan 28, 2009 12:18 pm

loop though text file

Post by inosent1 »

hi


i have a text file with 100 lines of data

i have the code to grab the text i am looking for in each line.

how do i read the text file, grab the text on each line, [process text - i have this code], then go to the next line in the text file, and just go down line by line until i get to the last line?

TIA
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: loop though text file

Post by Celauran »

Use file() to read the file into an array, then loop through the array?
User avatar
mecha_godzilla
Forum Contributor
Posts: 375
Joined: Wed Apr 14, 2010 4:45 pm
Location: UK

Re: loop though text file

Post by mecha_godzilla »

Hi,

Here is an example similar to what Celauran has just suggested:

Code: Select all

$filename_contents = file_get_contents('my_text_file.txt');
$lines = explode("\n", $filename_contents);
$number_of_lines = count($lines);

for ($i = 0; $i < $number_of_lines; $i++) {
	
	$lines[$i] = chop($lines[$i]);
	echo $lines[$i] . '<br />';
	
}
Note that text files saved on either Windows or Un*x will work because the end of line (EOL) character will still be matched even though their EOL characters are different ("\n" for Un*x, "\r\n" for Windows) but this might not work with files saved on Mac. Technically, Mac OS X is Un*x now anyway but some applications use the older Mac EOL ("\r") character.

HTH,

Mecha Godzilla
inosent1
Forum Commoner
Posts: 97
Joined: Wed Jan 28, 2009 12:18 pm

Re: loop though text file

Post by inosent1 »

thanks. works perfectly
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: loop though text file

Post by AbraCadaver »

I would use Celauran's suggestion as it is:

Code: Select all

$lines = file('file.txt', FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
    //do something with $line
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
Post Reply