John Davidson

php - Get a specific variable from external page

0 comments
Message:


I have no expertise in Curl, php or json. I need to get a specific variable from an external page in order to store it later in my mysql database. In this case, I need to get the result value from "transferencia" under the label USD. I tried some examples given from different pages but no success.
The page to extract the value is https://s3.amazonaws.com/dolartoday/data.json


I tried this code, but prints an array, I only need one value.


$ch = curl_init(); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, "https://s3.amazonaws.com/dolartoday/data.json?dolarp=$transferencia");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);
$json = json_decode($res, true);
print_r($json);

I will appreciate it!



My Answer:
You can access the specific variable you need by using the key "USD" and then accessing the "transferencia" value within that key. Here's an example code snippet that should help you achieve this:

php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, "https://s3.amazonaws.com/dolartoday/data.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);
$json = json_decode($res, true);

// Access the USD key and then the transferencia value within it
$usdTransferencia = $json['USD']['transferencia'];

echo $usdTransferencia;


This code will output the value of "transferencia" under the "USD" key from the external page. You can then store this value in your MySQL database as needed.

Rate this post

5 of 5 based on 7874 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us