Forum Moderators: coopster

Message Too Old, No Replies

Generating variables from a txt file

         

sauce

10:12 pm on Oct 18, 2005 (gmt 0)

10+ Year Member



Here's wqhat I'm trying to do... I'm trying to opne a text file and with keywords listed ex:

keyword1
keyword2
keyword3
keyword4
etc...

and have them automatically put into variables

$key1 = keyword1
$key2 = keyword1
$key3 = keyword1
$key4 = keyword1
etc...

I've been racking my brain trying everything and I can't get any results... nyone know an easy way?

jatar_k

10:33 pm on Oct 18, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



write it in a loop using a counter and variable variable names

<?  
$sfp = fopen('/path/to/file.txt','r');
$counter = 1;
while ($line = fgets($sfp)) {
${'key' . $counter} = $line;
$counter++;
}
fclose($sfp);
?>

you now have as many variables as there are lines in the file. Each variable is in the format you mentioned $key1, $key2 etc.

they will have line endings in the strings so you may want to replace \n or \r or both in the var $line when you assign to $keyX

but that will work