Jump to content

Reading values from a txt file to populate an array


unknown101

Recommended Posts

 

Hi Guys,

 

Just wondering if anyone could help me to read in values from a text file and then use this to populate an array.

 

$myFile = "Filename";
$fh = fopen($myFile, "r");
$line = fgets($fh);

 

So basically I want to read in each value (stored on seperate lines) and then put each one into an array.. could anyone give me an example of this or point me in the right direction?

 

Thanks in advance

 

You can do this at least three different ways:

One:

<?php
$array = array_map('trim',file('Filename'));
echo '<pre>' . print_r($array,true) . '</pre>';
?>

Two:

<?php
$array = explode("\n",file_get_contents('Filename'));
echo '<pre>' . print_r($array,true) . '</pre>';
?>

Three:

<?php
$myFile = "Filename";
$array = array();
$fh = fopen($myFile, "r");
while (!feof($fh)) {
        $array[] = fgets($fh, 4096);
    }
fclose($handle);
echo '<pre>' . print_r($array,true) . '</pre>';
?>

 

Ken

Thanks for the quick reply guys.

 

Mayb you see the problem with this code...

 

do
   {
   $names = array("$line");
   
   		foreach ($names as $value)
   			 {
		$count++;
		echo $count;
		echo "Search: $value<BR>";

		if ( stripos($source, $value) )
   			echo 'The website grabbed has '. $value .' in it';

        else
        {
        echo 'The site does not have the search keyword in it<BR>';
         }
       }
}
while ( $line = fgets($fh, 1000));

 

Say for example $source variable contains all the text from a website.  Ive put in 4 values in the text file which i know are in the site, but it only prints out that its grabbed the keyword on the last value not the first 3??  It goes through the loop the correct amount of times but just doesnt say its found the word.  Watever word I put last in the txt file it works with sucessfully? Do you have any suggestions as to why this is happening?

 

Thanks in advance

 

If I assume that any line in your file has more than one word, you can replace this line:

$names = array("$line");

to:

$names = split(" ", $line);   // if words are separated by spaces
// or
$names = split(",", $line);   // if comma-separated

 

The other thing is that you should have a $line = fgets($fh, 1000) statement before your do loop, or replace your do .. while loop into simply a while loop.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.