jaguar jaguar - 2 months ago 8
PHP Question

Which function in PHP would allow me to read contents of a file into a variable

Which function in PHP would allow me to read contents of a file and place them into a variable?

For example, I have a file named "my_text.txt" and the contents of that file are: "I am happy!". So, I would want a function that would read that string and place it into a variable named, say, as "myline".

As I have learned here, the readfile function can't do that.

Answer

you can use this code read a file

 <?php
    $myfile = fopen("my_text.txt", "r") or die("Unable to open file!");
   //just show/ echo the contents of the file
    echo fread($myfile,filesize("my_text.txt"));

   //Assign a value if you want and then echo
    $fileContents = fread($myfile,filesize("my_text.txt"));
    echo $fileContents;
    fclose($myfile);
    ?>

You can learn more about it in www.w3schools.com if you like. this php code first check the file availability if file found than this code shows you result or content of the file.But remember the location of the file in your directory. Hope this will work for you.

Comments