Jump to content

Archived

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

Singularity

Read a File and Store Whatevers In It Into A Variable

Recommended Posts

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!

Share this post


Link to post
Share on other sites
[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.

Regards
Liam

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
It will still contain newline chars with file_get_contents(), outputting is a lot easier with a string than an array.

Share this post


Link to post
Share on other sites

×

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.