In PHP, there are multiple approaches to retrieve the HTML code of a web page. Let's explore two common methods:
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.
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!