How can file_get_contents() and cURL be utilized to fetch data from an external page in PHP?
When fetching data from an external page in PHP, you can use either file_get_contents() or cURL. file_get_contents() is a simple way to retrieve the content of a URL, while cURL offers more advanced features and capabilities for handling HTTP requests. To fetch data using file_get_contents(), simply pass the URL as a parameter. For cURL, you need to initialize a cURL session, set the URL, execute the session, and then close it to fetch the data.
// Using file_get_contents()
$url = 'https://www.example.com/data';
$data = file_get_contents($url);
echo $data;
// Using cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.example.com/data');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Keywords
Related Questions
- What best practices should be followed when querying and displaying data from a MySQL database in PHP?
- In what ways can PHP and Flash be combined to enhance user experience on a website?
- What are the potential advantages of using a database over a CSV file for storing and retrieving data in PHP applications?