Hi. I have a text file (example.txt) of lines which have a variable in them, like so: blah blah blah blah blah $word blah blah blah blah $word blah blah I then have a script which pulls 1 line from the text file at random, like so: $namefile = "example.txt"; $handle = fopen($namefile, "r"); $contents = fread($handle, filesize($namefile)); fclose($handle); $word1 = explode("\r", $contents); $result = $word1[rand(0, count($word1)-1)]; The variable doesn't get read when I try and echo it like this: echo "<p class='res'>$result</p><br />"; How can I echo the variable I have placed in the text file ? Thanks in advance.
$word1 = explode("/n", $contents); $count = count($word1); $count = $count-1; $rand = rand(0,$count); $result = $word1[$rand]; echo $result; this should work. if not check the file if it even got lines and its not a huge line that wraps.
Hint: $namefile = "example.txt"; $handle = fopen($namefile, "r"); $contents = fread($handle, filesize($namefile)); fclose($handle); $word1 = explode("\r", $contents); // Does the same as $word1 = file("example.txt"); PHP:
The code pulls 1 line at random from the file (example.txt) - The code does this fine already. My problem is that the variable is being echoed literally as "$word" instead of what got posted from a form. So, lets say the word posted was 'test' and the line that gets selected at random from example.txt was: This is a $word It will echo it as: "This is a $word", instead of "This is a test"
Ever thought bout storing your variables in the text file as a serialized format? Example: <? $name = "bob"; $people = array("James", "John", "Mary", "Paul"); $money = 4.58; $all_together_now = array("Someone" => $name, "People" => $people, "Money" => $money); $newtext = serialize($all_together_now); echo $newtext; ?> PHP: would produce a string such as this: a:3:{s:7:"Someone";s:3:"bob";s:6:"People";a:4:{i:0;s:5:"James";i:1;s:4:"John";i:2;s:4:"Mary";i:3;s:4:"Paul";}s:5:"Money";d:4.5800000000000000710542735760100185871124267578125;} Code (markup): IF you load up the same string (say in a variable called $data after reading it in from a file) $newcode = unserialize($data); echo $newcode['Money']."\n"; echo $newcode['People'][1]; PHP: You'd get this: 4.58 John Code (markup): Essentially serialize/unserialize allows you to convert PHP objects into a string so that they can be stored or transmitted and then unserialize converts it back into a PHP object (such as an array). Making storing and recovery much easier.
Premiumscripts, in this situation $word is actually a capitalized version of $_POST['word'] (Thats a bit further up in the script I have made). So $word is a valid variable, its just it is being taken literally when I echo it from the text file.