How can you efficiently retrieve and display data from an external API in a PHP loop?
To efficiently retrieve and display data from an external API in a PHP loop, you can use the cURL library to make HTTP requests to the API endpoint, retrieve the data, decode the JSON response, and then loop through the data to display it on your webpage.
<?php
$api_url = 'https://api.example.com/data';
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if ($data) {
foreach ($data as $item) {
echo "<p>{$item['name']}: {$item['value']}</p>";
}
} else {
echo "Error retrieving data from API.";
}
?>
Keywords
Related Questions
- What are potential reasons for a PHP script to save images in lower resolution than the maximum supported by the camera?
- Are there any recommended resources or tutorials for learning how to update data based on checkbox selections in PHP?
- Are there any potential pitfalls to be aware of when using array_merge_recursive in PHP?