View Full Version : read webpage content in to a variable

03-21-2009, 01:25 PM
read web content via a weblink like


what is the correct way to do this?

03-21-2009, 01:37 PM
You could do it like this:


$file = "http://www.example.com";

$handle = fopen($file, "r");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);

// $contents will now contain the contents of the file


It's not been tested, but try it? I've basically pulled it from the PHP manual.

03-21-2009, 02:37 PM
The only problem with doing it this way is you want to get the filesize of the file to read to tell the fread() (http://uk.php.net/manual/en/function.fread.php) function the size of file. Like so

$contents .= fread($handle, filesize($file));

However filesize() (http://uk.php.net/manual/en/function.filesize.php) doesn't work on files that are not hosted on the same server that the script is running on. For instance i can get $filesize("my_file.txt") if my_file.txt is hosted on my server, but I can't get $filesize("http://www.example.com")

A better way to do this is using the file_get_contents() (http://uk.php.net/manual/en/function.file-get-contents.php) function. Does the same thing but doesn't require to know the size of the file and is smaller code :)

echo $contents;