Singularity Posted August 25, 2006 Share Posted August 25, 2006 This must be a stupid question, but what is the code to read a textfile and store it into a variable? Example:I have a text file called "number.txt" with the number "9" in it.I have another file called "index.php" that is in the same directory. Using PHP, I want to be able to declare a variable for example "$thenumber" that is equal to whatever number is in the number.txt file.Please help! Quote Link to comment https://forums.phpfreaks.com/topic/18640-read-a-file-and-store-whatevers-in-it-into-a-variable/ Share on other sites More sharing options...
shocker-z Posted August 25, 2006 Share Posted August 25, 2006 [code]$thenumber=file('number.txt');[/code]That should do the job mate.. puts it into an array.. to read it back you would have to use somthing like this.[code]foreach($thenumber as $number) {echo $number.'<Br>';}[/code]If you only have 1 line then i beleave it is stored in the variable instead of an array.RegardsLiam Quote Link to comment https://forums.phpfreaks.com/topic/18640-read-a-file-and-store-whatevers-in-it-into-a-variable/#findComment-80319 Share on other sites More sharing options...
Jenk Posted August 25, 2006 Share Posted August 25, 2006 file_get_contents() Quote Link to comment https://forums.phpfreaks.com/topic/18640-read-a-file-and-store-whatevers-in-it-into-a-variable/#findComment-80326 Share on other sites More sharing options...
HuggieBear Posted August 25, 2006 Share Posted August 25, 2006 If you know the file only contains one line, then best to use file_get_contents() as per Jenk's post.This will return the contents of the file in a string as opposed to an array.Rich Quote Link to comment https://forums.phpfreaks.com/topic/18640-read-a-file-and-store-whatevers-in-it-into-a-variable/#findComment-80328 Share on other sites More sharing options...
Jenk Posted August 25, 2006 Share Posted August 25, 2006 It will still contain newline chars with file_get_contents(), outputting is a lot easier with a string than an array. Quote Link to comment https://forums.phpfreaks.com/topic/18640-read-a-file-and-store-whatevers-in-it-into-a-variable/#findComment-80329 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.