Jump to content


Photo

Read a File and Store Whatevers In It Into A Variable


  • Please log in to reply
4 replies to this topic

#1 Singularity

Singularity
  • New Members
  • Pip
  • Newbie
  • 5 posts

Posted 25 August 2006 - 12:58 PM

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!

#2 shocker-z

shocker-z
  • Members
  • PipPipPip
  • Advanced Member
  • 864 posts
  • LocationNottingham

Posted 25 August 2006 - 01:14 PM

$thenumber=file('number.txt');


That should do the job mate.. puts it into an array.. to read it back you would have to use somthing like this.

foreach($thenumber as $number) {
echo $number.'<Br>';
}

If you only have 1 line then i beleave it is stored in the variable instead of an array.

Regards
Liam
www: www.ukchat.ws | irc: irc.ukchat.ws chan: #blufudge

#3 Jenk

Jenk
  • Members
  • PipPipPip
  • Advanced Member
  • 778 posts

Posted 25 August 2006 - 01:31 PM

file_get_contents()

#4 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 25 August 2006 - 01:44 PM

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
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#5 Jenk

Jenk
  • Members
  • PipPipPip
  • Advanced Member
  • 778 posts

Posted 25 August 2006 - 01:47 PM

It will still contain newline chars with file_get_contents(), outputting is a lot easier with a string than an array.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users