Home  >  Article  >  Backend Development  >  How to Retrieve the HTML Code of a Web Page in PHP?

How to Retrieve the HTML Code of a Web Page in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 09:45:02635browse

How to Retrieve the HTML Code of a Web Page in PHP?

Retrieving HTML Code of a Web Page in PHP

In order to obtain the HTML code of a web page using PHP, you can utilize the following approaches:

Using fopen()

If your PHP server supports URL fopen wrappers, you can retrieve the HTML code using the simple method:

<code class="php">$html = file_get_contents('https://stackoverflow.com/questions/ask');</code>

Using cURL

For enhanced control, consider using the cURL functions:

<code class="php">$c = curl_init('https://stackoverflow.com/questions/ask');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
// Customize additional options as desired

$html = curl_exec($c);

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

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

curl_close($c);</code>

Output:

The $html variable will now hold the HTML code of the specified web page.

The above is the detailed content of How to Retrieve the HTML Code of a Web Page in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn