PHP: how can I load the content of a web page into a variable?

Provided allow_url_fopen is enabled, you can just use file_get_contents :

$my_var = file_get_contents('http://yoursite.com/your-page.html');

And, if you need more options, take a look at Stream Functions -- there is an example on the stream_context_create manual page where a couple of HTTP-headers are set.


If allow_url_fopen is disabled, another solution is to work with curl -- means a couple more lines of code, though.

Something as basic as this should work in the simplest situations :

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://stackoverflow.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$my_var = curl_exec($ch);
curl_close($ch);

But note that you might need some additional options -- see the manual page of curl_setopt for a complete list.

For instance :

  • I often set CURLOPT_FOLLOWLOCATION, so redirects are followed.
  • The tiemout-related options are quite often useful too.

The code below stores the content of the site w3schools.com into a variable.

$my_var = file_get_contents('http://www.w3schools.com');

echo $my_var;

Tags:

Php