Fetch API Data: Associate URLs
To achieve this, you can use the cURL library in PHP to send a GET request to the specified API endpoint and retrieve the response. Here's an example of how you can accomplish this:
php<?php
function fetchData() {
$url = "https://example.com/api";
$headers = [
'x-api-key: Atg'
];
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
if ($response === false) {
$error = curl_error($curl);
curl_close($curl);
throw new Exception("cURL request failed: " . $error);
}
curl_close($curl);
return json_decode($response, true);
}
$data = fetchData();
$associativeArray = [];
foreach ($data as $item) {
$vdpUrl = $item['VDPUrl'];
$currentCountry = $item['CurrentCountry'];
$associativeArray[$vdpUrl] = $currentCountry;
}
print_r($associativeArray);
?>
In the above code, we defined a function called fetchData()
that handles the cURL request to the API endpoint. The response is then decoded from JSON to an associative array using json_decode()
. Next, we loop through each item in the array and extract the VDPUrl
and CurrentCountry
values. We then store these values as key-value pairs in the $associativeArray
. Finally, we print the resulting associative array using print_r()
.
Note that you may need to adjust the code according to your specific API response structure. Also, ensure that the cURL extension is enabled in your PHP configuration for this code to work.