Home >Backend Development >PHP Tutorial >How to Retrieve HTML Code from a Web Page in PHP?

How to Retrieve HTML Code from a Web Page in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 03:06:28251browse

How to Retrieve HTML Code from a Web Page in PHP?

Retrieving HTML Code of a Web Page in PHP

In PHP, there are multiple approaches to retrieve the HTML code of a web page. Let's explore two common methods:

Using url fopen Wrappers

If your PHP server allows url fopen wrappers, you can fetch the HTML code using the file_get_contents function:

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

This method is simple and sufficient for basic needs.

Using cURL

For more advanced control, consider using the cURL functions:

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

// Set other desired cURL options here...

$html = curl_exec($c);

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

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

curl_close($c);</code>

cURL provides greater flexibility and allows you to customize various aspects of the request, such as headers, cookies, and authentication.

The above is the detailed content of How to Retrieve HTML Code from 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