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

Barbara Streisand
Release: 2024-11-01 03:06:28
Original
140 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!