Here is the code
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpClient\HttpClient;
class ApiController extends AbstractController
{
/**
* @Route("/api/fetch-data", name="api_fetch_data")
*/
public function fetchData(): Response
{
// Fetch data from API
$client = HttpClient::create();
$response = $client->request('GET', 'https://anyapi.io/api/v1/exchange/rates?apiKey=960k8dih5kouba5h0luhu8aghl7nnc4no8q6ung7lcvgj64bm5ic2i8');
$data = $response->getContent();
// $data = json_decode($response->getContent(), true);
// Process data
$data = json_decode($data, true);
// ...
// Access the data in the PHP object
$timestamp = $data['timestamp'];
$base_currency = $data['source'];
$rates = $data['quotes'];
// Print the formatted data
echo "Timestamp: " . date('Y-m-d H:i:s', $timestamp) . "\n";
echo "Base currency: " . $base_currency . "\n";
foreach ($rates as $currency => $rate) {
echo $currency . ": " . $rate . "\n";
}
// Return response
return $this->json([
'data' => $data,
]);
}
}
I see a "lastUpdate" but no "timestamp", just change the name in your code. Same for "source" => base and "quotes" => rates.
The output:
*Array
(
[lastUpdate] => 1678320000
[base] => EUR
[rates] => Array
(
[EUR] => 1
[USD] => 1.0554
)
)*