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

Barbara Streisand
Release: 2024-11-01 19:54:30
Original
335 people have browsed it

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

Retrieving HTML Code of a Web Page in PHP

Getting the HTML code of a web page can be useful for various purposes, such as scraping data or creating custom parsers. In PHP, there are different ways to accomplish this task.

Using the file_get_contents Function

If your PHP server permits the use of URL fopen wrappers, you can use the file_get_contents() function to directly retrieve the HTML code. For instance:

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

Keep in mind that the URL fopen wrappers must be enabled in your server's PHP configuration for this method to work.

Using cURL Functions

For greater control and customization, you can utilize the cURL functions. Here's a sample code using cURL:

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

$html = curl_exec($c);

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

$status = curl_getinfo($c, CURLINFO_HTTP_CODE);

curl_close($c);</code>
Copy after login

This code establishes a cURL session, sets the CURLOPT_RETURNTRANSFER option to indicate it should return the output, and retrieves the HTML code into a variable. It also obtains the HTTP status code for reference.

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