Home >Backend Development >PHP Tutorial >How to Send GET Requests in PHP Using `file_get_contents()` or cURL?
Sending GET Requests in PHP
In PHP, sending HTTP GET requests to URLs and retrieving their contents is a common task. To achieve this, PHP offers a few options:
Using file_get_contents()
The file_get_contents() function can be utilized to directly obtain the contents of a URL as a string. This approach is straightforward for basic use cases where only the file's contents are required.
$xml = file_get_contents("http://example.com/file.xml");
Using cURL
If you require more flexibility or control over the HTTP request, cURL is a recommended alternative. It provides a wide array of options to customize the request, such as setting headers, authentication, and managing cookies.
$ch = curl_init("http://example.com/file.xml"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $xml = curl_exec($ch); curl_close($ch);
Example Usage
In the example scenario where you want to download XML contents from a URL, you can choose either approach based on your specific requirements. If you need just the XML content, file_get_contents() is quicker and easier. However, if you need more control over the request, such as authentication or setting headers, cURL is the better choice.
The above is the detailed content of How to Send GET Requests in PHP Using `file_get_contents()` or cURL?. For more information, please follow other related articles on the PHP Chinese website!