11

How can I load the content of a web page into a variable?

I need to store the HTML in a string.

the
  • 21,007
  • 11
  • 68
  • 101
aneuryzm
  • 63,052
  • 100
  • 273
  • 488

2 Answers2

28

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.
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
4

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;
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
SwR
  • 612
  • 1
  • 8
  • 21