Search code examples
phpfile-get-contentsfwritefread

Write to and then read from file using PHP


I'm trying to get the contents of a specific website, write the content to a .txt file and output unformatted result in my browser. I'm able to actually write the website content to my text file, but it won't echo out in my browser. I tried using "w+" and "r+" in my original handle but that didn't do the trick. What am I doing wrong here?

$file = file_get_contents('http://www.example.com');
$handle = fopen("text.txt", "w");
fwrite($handle, $file);
fclose($handle);

$myfile = "text.txt";
$handle = fopen($myfile, "r");
$read = htmlentities(fread($handle, filesize($myfile)));
echo $read;

Solution

  • Your initial statement of $file contains all of the formatted code from the file you just wrote so you can use that.

     echo htmlentities($file);
    

    However, several people have asked this already.. perhaps the OP wants to verify that the file was written correctly?

    Your code for opening looks fine, have you ruled out a permissions issue? check this by using is_readable($myFile) prior to opening it. You can also do an is_writable on the folder that your writing to to ensure that your actually writing the file.