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.";
}
?>