How can PHP be used to send HTTP requests to external servers for data retrieval?
To send HTTP requests to external servers for data retrieval in PHP, you can use the cURL extension. cURL is a library that allows you to connect and communicate with different types of servers using various protocols like HTTP, HTTPS, FTP, etc. You can use cURL functions in PHP to send GET or POST requests to external servers, retrieve data, and handle responses.
// Initialize cURL session
$ch = curl_init();
// Set the URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'http://example.com/api/data');
// Set the request method to GET
curl_setopt($ch, CURLOPT_HTTPGET, true);
// Set option to return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the request and fetch the response
$response = curl_exec($ch);
// Close cURL session
curl_close($ch);
// Output the response
echo $response;