I have an cURL file that will return an array like below and I wonder how can I declare the variable of [data]=>[id].I tried like $decoded.data or $decoded.[data] but it does not work.
Array
(
[data] => Array
(
[id] => 2
[email] => [email protected]
[first_name] => Janet
[last_name] => Weaver
[avatar] => https://reqres.in/img/faces/2-image.jpg
)
[support] => Array
(
[url] => https://reqres.in/#support-heading
[text] => To keep ReqRes free, contributions towards server costs are appreciated!
)
)
PHP file:
<?php
$ch = curl_init();
$url = "https://reqres.in/api/users/2";
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
$decoded = json_decode($resp,true);
print_r($decoded);
curl_close($ch);
?>
My Answer:
To declare a variable from the cURL response in PHP, you can use the `json_decode` function to convert the JSON response into an associative array. Here's an example of how you can do this:
php
// Your cURL request code here
// Assuming $response contains the JSON response from cURL
$response = '{"data": {"key1": "value1", "key2": "value2"}}';
// Decode the JSON response into an associative array
$data = json_decode($response, true);
// Access the 'data' key in the array
$dataArray = $data['data'];
// Now you can access the values in the 'data' array
echo $dataArray['key1']; // Output: value1
echo $dataArray['key2']; // Output: value2
In this example, we assume that the cURL response is stored in the variable `$response`. We then use `json_decode` with the second parameter set to `true` to convert the JSON response into an associative array. Finally, we access the 'data' key in the array to get the values stored within it.
Rate this post
5 of 5 based on 1021 votesComments