Home > Article > Backend Development > 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>
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>
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!