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

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

I need to store the HTML in a string.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

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;

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply