What is the best practice for retrieving and displaying data from an API using PHP?

When retrieving and displaying data from an API using PHP, it is best practice to make a request to the API using cURL or a similar library, parse the JSON response, and then display the data accordingly on your webpage. This ensures that the data is fetched securely and efficiently.

<?php
// API endpoint URL
$api_url = 'https://api.example.com/data';

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute cURL session
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);

// Decode JSON response
$data = json_decode($response);

// Display data
foreach ($data as $item) {
    echo $item->name . ' - ' . $item->value . '<br>';
}
?>