Hi,
I am new to php.I want to read a word by word from a file.When I use fgets it read line by line.When i use fread then it read full contents from a file.File_get_contents read a full contents from a file.

I need to read a each single word from a file and match the email..

Please help me..
Thanks in advance.

Prem

<?php
$handle = @fopen("/yourtextfile.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle);
        $exploded_data = explode(" ",$buffer);
    }
    fclose($handle);
}
?>

After reading the data from the file using fgets(), go through each line and explode the string to get each word.
Note: '$exploded_data' is an array. Also check the following.
http://php.net/manual/en/function.explode.php

Hi,
I am new to php.I want to read a word by word from a file.When I use fgets it read line by line.When i use fread then it read full contents from a file.File_get_contents read a full contents from a file.

I need to read a each single word from a file and match the email..

Please help me..
Thanks in advance.

Prem

What ever you do, it is going to be around this general idea

<?php
$arrFileContent = array();
$intLoopCounter = 0;

$file = fopen("file.txt", "r");
while(!feof($file))
{
	$strLineContent = fgets($file);
	if(trim($strLineContent) != "")
	{
		$arrFileContent[$intLoopCounter] = explode(" ", $strLineContent);
	}
	else
	{
		$arrFileContent[$intLoopCounter] = array();
	}
	$intLoopCounter++;
}
fclose($file);
?>

There are two things to note here.

I am sticking with fgets because I can read a file line by line without storing the entire text file in memory initially. Which is a good thing because I am parsing it out and then assigning it to a new array. If I used a function like file() I would easily double the required memory and this can get very sloppy and slow when dealing with large text files. Seriously, try not to go there.

Second, inside the loop you will see that I use explode() to parse out the line into words. This may not be perfect but it is a good start and you will probably have to tweak it a little to consider all scenarios.

<?php
$handle = @fopen("/yourtextfile.txt", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle);
        $exploded_data = explode(" ",$buffer);
    }
    fclose($handle);
}
?>

After reading the data from the file using fgets(), go through each line and explode the string to get each word.
Note: '$exploded_data' is an array. Also check the following.
http://php.net/manual/en/function.explode.php

You read my mind :)

You read my mind :)

yes indeed :)

Thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.