0

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

3
Contributors
5
Replies
15
Views
7 Years
Discussion Span
Last Post by prem2
0
<?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

0

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.

Edited by OS_dev: n/a

0
<?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 :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.