cURL and json data convert into array and get only temp data - php

I am new using json data. I am trying to call an api using cURL and converting it into array. I just want the temp data using foreach loop. But i am getting Invalid argument supplied for foreach() error. My code
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,"http://api.openweathermap.org/data/2.5/forecast/daily?q=dhaka%2Cbangladesh&mode=json&units=metric&cnt=3");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result = curl_exec($cSession);
curl_close($cSession);
//echo $result;
//$i = 3 as i am requesting 3 day data
for ($i=0; $i <3 ; $i++) {
foreach ($result as $value) {
echo $value['temp'][0]['day'];
echo $value['temp'][0]['min'];
echo $value['temp'][0]['max'];
echo $value['temp'][0]['night'];
echo $value['temp'][0]['eve'];
echo $value['temp'][0]['morn'];
}
}

This should work for you:
$json = json_decode($result);
$res = $json->{'list'};
foreach ($res as $value) {
echo $value->{'temp'}->{'day'} . "<br>";
echo $value->{'temp'}->{'min'} . "<br>";
echo $value->{'temp'}->{'max'} . "<br>";
echo $value->{'temp'}->{'night'} . "<br>";
echo $value->{'temp'}->{'eve'} . "<br>";
echo $value->{'temp'}->{'morn'} . "<br>";
}
In your query string you have the value metric&cnt=3 this is what you want for days to be extracted if you get from cnt=10 you will have 10 results. No need for a for loop.

With the curl_exec you'll get a json as a string, you have to parse it first to use it.
Try this: http://php.net/manual/en/function.json-decode.php
And don't forget to set the second parameter to true if you want the result as an array.

the result is JSON that you should parse with json_decode first
edit with more code:
...
$result = json_decode($result,true);
for ($i=0; $i <3 ; $i++) {
foreach ($result['list'] as $value) {
echo $value['temp']['day'];
echo $value['temp']['min'];
...

curl_exec with the option CURLOPT_RETURNTRANSFER set to true will return the result of fetch the url you have set so your variable $result is a STRING.
You hace to convert to an array:
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,"http://api.openweathermap.org/data/2.5/forecast/daily?q=dhaka%2Cbangladesh&mode=json&units=metric&cnt=3");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result = curl_exec($cSession);
curl_close($cSession);
$result = json_decode($result,true);
//echo $result;
//$i = 3 as i am requesting 3 day data
for ($i=0; $i <3 ; $i++) {
foreach ($result as $value) {
echo $value['temp'][0]['day'];
echo $value['temp'][0]['min'];
echo $value['temp'][0]['max'];
echo $value['temp'][0]['night'];
echo $value['temp'][0]['eve'];
echo $value['temp'][0]['morn'];
}
}

Related

Hi need help, how to get data

; this is what i've tried? for display : ADA/ETH bestAsk":0.000699,"bestBid":0.000607 ?
$url = "https://exchange-api.lcx.com/market/tickers";
$json = json_decode(file_get_contents($url), true);
$data = $json["data"];
$bestAsk = $json['bestAsk'];
$bestBid = $json['bestBid'];
echo $data;
echo $bestAsk;
echo $bestBid;
how to get data?
; any ideea?
This should get you started:
$url = "https://exchange-api.lcx.com/market/tickers";
$json = json_decode(file_get_contents($url), true);
$data = $json["data"];
foreach($data as $key => $value ){
#var_dump($value);
echo $key." - BESTBID:".$value["bestBid"]."\n";
echo $key." - BESTASK:".$value["bestAsk"]."\n";
}
output:
ADA/ETH - BESTBID:0.000607
ADA/ETH - BESTASK:0.000699
ADA/EUR - BESTBID:1.6681
ADA/EUR - BESTASK:2.2
ADA/LCX - BESTBID:28.1101
ADA/LCX - BESTASK:45
AMP/EUR - BESTBID:0.044
AMP/EUR - BESTASK:0.067839
AMP/LCX - BESTBID:0.85
AMP/LCX - BESTASK:1
....
Your code is working perfectly in my system and the data fetched successfully.
if you want to display JSON in PHP you can use print_r statement instead of echo:
print_r($data);
Your should try this one!
$url = "https://exchange-api.lcx.com/market/tickers";
$json = json_decode(file_get_contents($url), true);
$data = $json["data"];
foreach($data as $key => $value ){
#var_dump($value);
echo $key." - BESTBID:".$value["bestBid"]."\n";
echo $key." - BESTASK:".$value["bestAsk"]."\n";
}

How to iterate over an item of objects and array

I do not know how to iterate on this output, it can be simple but try several methods without success.
I have the result of a query that throws a json with objects and fixes, but I can not get the cpu, memory and disk values:
<?php
// How to read influx data with curl
$query = urlencode("select * from calls limit 1");
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 1); //timeout in seconds
curl_setopt($ch, CURLOPT_URL,"http://127.0.0.1:8086/query?db=myDB&q=$query");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$res = json_decode(curl_exec ($ch));
curl_close ($ch);
var_dump($res);
?>
and I get this output:
{"results":[{"statement_id":0,"series":[{"name":"custom","tags":{"hostname":"LINUX01"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",1,78,0,0]]},{"name":"custom","tags":{"hostname":"LINUX02"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",6,48,0,0]]},{"name":"custom","tags":{"hostname":"LINUX03"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",5,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX04"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",35,94,0,0]]},{"name":"custom","tags":{"hostname":"LINUX05"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",3,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX06"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",57,25,0,0]]},{"name":"custom","tags":{"hostname":"LINUX07"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX08"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",41,30,0,0]]},{"name":"custom","tags":{"hostname":"ues90078"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,20,0,0]]},{"name":"custom","tags":{"hostname":"LINUX09"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,45,0,0]]},{"name":"custom","tags":{"hostname":"LINUX041"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",31,30,0,0]]},{"name":"custom","tags":{"hostname":"LINUX042"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,8,0,0]]},{"name":"custom","tags":{"hostname":"LINUX043"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",54,10,0,0]]}]}]}
Try for example:
foreach ($res as $test) {
echo $test->statement_id->cpu;
}
I wish I could get this:
hostname time cpu mem load load
linux01 1970-01-01T00:00:00Z 1 78 0 0
Sorry for my bad English.
You will have a difficult time working with this data as is, because most of the data is unkeyed, and that makes it misleading to work with as an object. It would be easier in this case if you worked with the array. You can do this by using true as the second parameter of the decode.
$data = json_decode(curl_exec ($ch), true);
$results = $data['results'];
foreach ($results['series'] as $server) {
$cpuIndex = array_search('cpu', $server['columns']);
echo $server['values'][$cpuIndex];
}
You need to convert it to from JSON to an Object or Array.
Here's a common Array situation:
$results = json_decode('{"results":[{"statement_id":0,"series":[{"name":"custom","tags":{"hostname":"LINUX01"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",1,78,0,0]]},{"name":"custom","tags":{"hostname":"LINUX02"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",6,48,0,0]]},{"name":"custom","tags":{"hostname":"LINUX03"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",5,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX04"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",35,94,0,0]]},{"name":"custom","tags":{"hostname":"LINUX05"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",3,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX06"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",57,25,0,0]]},{"name":"custom","tags":{"hostname":"LINUX07"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX08"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",41,30,0,0]]},{"name":"custom","tags":{"hostname":"ues90078"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,20,0,0]]},{"name":"custom","tags":{"hostname":"LINUX09"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,45,0,0]]},{"name":"custom","tags":{"hostname":"LINUX041"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",31,30,0,0]]},{"name":"custom","tags":{"hostname":"LINUX042"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,8,0,0]]},{"name":"custom","tags":{"hostname":"LINUX043"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",54,10,0,0]]}]}]}', true);
foreach ($results["results"][0]["series"] as $array) {
echo "<table>";
echo "<thead>";
echo "<tr>";
foreach ($array["columns"] as $value) {
echo "<th>{$value}</th>";
}
echo "</tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
foreach ($array["values"][0] as $value) {
echo "<td>{$value}</td>";
}
echo "</tr>";
echo "</tbody>";
echo "<table>";
}
If you want something specific:
foreach ($results["results"][0]["series"] as $array) {
foreach ($array["columns"] as $key => $value) {
if ($value === "cpu") $column = $key;
}
echo "cpu: {$array["values"][0][$column]}.<br>";
}
To add hostname, simple add:
echo "<tr>";
echo "<th colspan=" . count($array["columns"]) . ">{$array["tags"]["hostname"]}</th>";
echo "</tr>";
after echo "<thead>";.

How to echo JSON data using PHP

{
USD_INR: {
2017-12-31: 63.830002
},
INR_USD: {
2017-12-31: 0.015667
}
}
I have tried with following method,
$url = file_get_contents("https://free.currencyconverterapi.com/api/v5/convert?q=USD_INR,INR_USD&compact=ultra&date=2017-12-31");
$result = json_decode($url);
echo $result->USD_INR;
but it did't works, can any one help me where I'm doing wrong.
Just pass date in $todaysDate variable which you want price.
$todaysDate = "2017-12-31";
$url = file_get_contents("https://free.currencyconverterapi.com/api/v5/convert?q=USD_INR,INR_USD&compact=ultra&date=$todaysDate");
$result = json_decode($url);
echo ($result->USD_INR->$todaysDate);
You can add true as a second parameter on json_decode to make it associative array.
$url = file_get_contents("https://free.currencyconverterapi.com/api/v5/convert?q=USD_INR,INR_USD&compact=ultra&date=2017-12-31");
$result = json_decode($url, true);
And access it as:
echo $result["USD_INR"]["2017-12-31"];
This will result to: 63.830002
Doc: http://php.net/manual/en/function.json-decode.php
You can foreach loop to get all the values
$url = file_get_contents("https://free.currencyconverterapi.com/api/v5/convert?q=USD_INR,INR_USD&compact=ultra&date=2017-12-31");
$result = json_decode($url, true);
foreach ( $result as $value ) {
foreach ( $value as $date => $rate ) {
echo $date . ": " . $rate . "<br />";
}
}
This will result to:
2017-12-31: 63.830002
2017-12-31: 0.015667
You are trying to echo an object either use print_r like this to print USD_INR
$url = '{"USD_INR":{"2017-12-31":63.830002},"INR_USD":{"2017-12-31":0.015667}}';
$result = json_decode($url);
print_r($result->USD_INR);
OR to echo value of 2017-12-31 inside USD_INR
$url = '{"USD_INR":{"2017-12-31":63.830002},"INR_USD":{"2017-12-31":0.015667}}';
$result = json_decode($url);
echo $result->USD_INR->{'2017-12-31'};
Using {'2017-12-31'} because 2017-12-31 is not proper variable name
Live demo

Print each element of json curl execution

I have a curl function to call a service that return output like this
[{"idpacket":1,"packetname":"Silver","packetdesc":"Silver is da best","packetprize":"Rp 20000","packettime":"365 days"}]
I wanna echo all of element into table row
How i do that? I always get error on foreach function. Please help
This is my code:
<?php
//step1
$cSession = curl_init();
//step2
curl_setopt($cSession,CURLOPT_URL,"http://localhost:8080/packet");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
//step3
$result=curl_exec($cSession);
//step4
curl_close($cSession);
//
foreach ((array) $result as $item) {
print_r($item['idpacket']);
}
?>
Thank you :)
I got this conclusion as I understood
write this code and check :
print_r((array)$result);
its place your JSON into an array does not decode your JSON like this:
Array
(
[0] => [{"idpacket":1,"packetname":"Silver","packetdesc":"Silver is da best","packetprize":"Rp 20000","packettime":"365 days"}]
)
if you want to access 'idpacket'
write like this:
$result_array = json_decode($result,true);
foreach ((array) $result_array as $item) {
print_r($item['idpacket']);
}
You could write something like
<?php
$resultArr = json_decode($result,true);
$header="<tr>";
$row="<tr>";
echo "<table>";
foreach($resultArr[0] as $col => $val)
{
$header.="<td>".$col."</td>";
$row.="<td>".$val."</td>";
}
$header.="</tr>";
$row.="</tr>";
echo $header;
echo $row;
echo "</table>";
?>

How to go through each element in JSON array in PHP

I want to echo out each element of an object of a JSON array like this:
{"request_list":[{"id":"1","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null},{"id":"3","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null}]}
But i cannot do it.I tried somethinglikethis:
$object = json_decode($json, true);
$request_list = $object->request_list;
foreach($request_list as $r){
echo $r->name;
echo $r->blood_type;
echo $r->phone_number;
}
But I got an error like:
Invalid argument supplied for foreach()
As you have mark return as array true in json_decode. So, try below code.
$object = json_decode($json, true);
$request_list = $object['request_list'];
foreach($request_list as $r){
echo $r['name'];
echo $r['blood_type'];
echo $r['phone_number'];
}
Use this
$object = json_decode($json, true);
$request_list = $object['request_list'];
foreach($request_list as $r){
echo $r['name'];
echo $r['blood_type'];
echo $r['phone_number'];
}
try
$json = '{"request_list":[{"id":"1","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null},{"id":"3","name":"yunus","surname":"smsk","phone_number":"05350601922","blood_type":"0","unit_of_blood":"0","date":null}]}';
$data = json_decode($json );
$request = $data->request_list;
foreach($request as $request_data){
echo $request_data->id;
echo $request_data->name;
echo $request_data->surname;
}

Categories