...

View Full Version : read webpage content in to a variable



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

http://www.site.com/?id=123

what is the correct way to do this?

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

<?php

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

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

// $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.

timgolding
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 :)



<?PHP
$contents='';
$contents.=file_get_contents("http://www.example.com");
echo $contents;
?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum