[SOLVED] count entries and echo results

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
User avatar
fresh
Forum Contributor
Posts: 259
Joined: Mon Jun 14, 2004 10:39 am
Location: Amerika

count entries and echo results

Post by fresh »

Hey,

I have a text file that holds a list of names like so:
john
josh
jason
susan
each on their own line.. and I would like to open this file and count each entry and store that value in a variable, so I could then echo that value to my web page.. thanks :)
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

This is one way

Code: Select all

$server_path = $_SERVER['DOCUMENT_ROOT'];

// open the data file
($fp = fopen($server_path."/path/to/datafile/names.txt", 'r')) or die ("Couldn't open the data file");

$count = 0;
	
// Iterate through each line of the file
while ( ! feof($fp) ) {
	$count++;
}

// output the result
echo $count;
User avatar
fresh
Forum Contributor
Posts: 259
Joined: Mon Jun 14, 2004 10:39 am
Location: Amerika

Post by fresh »

hey it isn't working, it just keeps looping and I keep getting a fatal error, maxim time 30 seconds allowed..

I am using that exact code above.. any help? Thanks :)
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

show me the code you have done.

Have you got the correct path tot he file.
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

An alternative....

Code: Select all

<?php

if (FALSE !== ($lines = @file('/path/to/file')))
{
  $n_lines = count($lines);
  // for large files unset lines array unless you plan
  // to use it for something else.
  unset($lines);
}
else
{
  // failed to open file
  $n_lines = 0;
}

echo $n_lines;
?>
User avatar
fresh
Forum Contributor
Posts: 259
Joined: Mon Jun 14, 2004 10:39 am
Location: Amerika

Post by fresh »

alright.. that works great, thank you guys :)
Post Reply