How do I get the HTML code of a web page in PHP?


Question

I want to retrieve the HTML code of a link (web page) in PHP. For example, if the link is

https://stackoverflow.com/questions/ask

then I want the HTML code of the page which is served. I want to retrieve this HTML code and store it in a PHP variable.

How can I do this?

1
76
5/23/2017 12:26:33 PM

Accepted Answer

If your PHP server allows url fopen wrappers then the simplest way is:

$html = file_get_contents('http://stackoverflow.com/questions/ask');

If you need more control then you should look at the cURL functions:

$c = curl_init('http://stackoverflow.com/questions/ask');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
//curl_setopt(... other options you want...)

$html = curl_exec($c);

if (curl_error($c))
    die(curl_error($c));

// Get the status code
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);

curl_close($c);
116
9/3/2013 2:12:40 PM

Also if you want to manipulate the retrieved page somehow, you might want to try some php DOM parser. I find PHP Simple HTML DOM Parser very easy to use.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon