Reading files with php question

Associate
Joined
19 Jun 2006
Posts
162
Location
Swansea, Wales
Hey guys,

I have a text file with one word on each new line...

a
aardvark
apple
...
zebra

I want to read each line from the file, perform a comparison then read the next line.

However, I just keep reading ALL the lines up the line I am at in the loop.

E.g.
I want to read line 1 - I read line 1
I want to read line 2 - I read line 1 and 2
I want to read line 3 - I read line 1 and 2 and 3

This is my code...

Code:
<?php

	$myWord = "apple";

	$fp = @fopen("names/NAMES.DIC", "r")
		or die ("Could not find file");
	
	$data = "";

	while(!feof($fp)) {
		$data .= fgets($fp, 4096);
		echo $data."<br />";
		$output = strcmp($data, $myWord);
		echo " ".$output;
		if ($output == 0) {
			echo "Word found! The word is " + $data;
			break;
		}
	}

	fclose($fp);

?>

Any help much appreciated!
 
Code:
        while(!feof($fp)) {
                $data = trim(fgets($fp, 4096));
                echo $data."<br />";
                if (strcmp($data, $myWord) == 0) {
                        echo "Word found! The word is $data";
                        break;
                }
        }

$data .= is adding the previous value of $data to itself each time, hence what you were seeing. See http://uk2.php.net/manual/en/language.operators.string.php.

However, strcmp() won't return a match for the $data, because each line ends with a new-line. So, you can trim() $data to check just the word.

One last issue. echo "Word found! The word is " + $data - the plus operator does not concatenate strings in PHP, use the . operator for this, or just enclose the whole string in "double quotes" for it to be evaluated.
 
Back
Top Bottom