user1781186
user1781186

Reputation:

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;

Upvotes: 2

Views: 2033

Answers (3)

Baba
Baba

Reputation: 95103

You don't need to open the files multiple times .. just try

$file = "log.txt";
$url = 'http://www.stackoverflow.com' ;

$handle = fopen("log.txt", "w+");
fwrite($handle, file_get_contents($url));
rewind($handle);

$read = htmlentities(fread($handle, filesize($file)));
echo $read;

Upvotes: 1

Ne Ma
Ne Ma

Reputation: 1709

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.

Upvotes: 1

Youri
Youri

Reputation: 505

You can var_dump() the $handle and see if it can be opened. If yes, var_dump($read)..

And to read files you can also use file_get_contents().

Upvotes: 0

Related Questions