How to echo JSON data using PHP - 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

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";
}

Unserialize function doesn't return array values

Hello i want to unserialize an array in order to display the array values.
The way that the array is inserted to my db field is like this.
persons: "a:1:{i:0;s:55:"[{"value":"john: writer"},{"value":"john: producer"}]";}"
and the function i have done but i am not getting any results is this
$adDetails = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($adDetails as $feed) {
$feed->logo_pic = SITE_URL . $feed->logo_pic;
$feed->image_path = SITE_URL . $feed->image_path;
$feed->media_pic = SITE_URL . 'mediaPic/' . $feed->media_pic;
$personsArr = unserialize(array($feed->persons));
$personsText = " ";
if(!empty($personsArr)){
list($firstItem) = $personsArr;
foreach ($firstItem as $key => $value) {
foreach ($value as $valueInner) {
$personsText .= $valueInner.", ";
}
}
}
$feed->personsNew = $personsText;
}
$response['success'] = true;
$response['adDetails'] = $adDetails;
echo json_encode($response);
I am getting nothing on personsText although persons is persons: "a:1:{i:0;s:55:"[{"value":"john: writer"},{"value":"john: producer"}]";}"
Any help?
The value in the array is a JSON string, so you need to decode it.
The argument to unserialize() should just be $feed->persons, it shouldn't be in an array.
Instead of the loop, you can use array_column() to get all the value elements, and implode() to combine them with comma delimiters.
$adDetails = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($adDetails as $feed) {
$feed->logo_pic = SITE_URL . $feed->logo_pic;
$feed->image_path = SITE_URL . $feed->image_path;
$feed->media_pic = SITE_URL . 'mediaPic/' . $feed->media_pic;
$personsArr = unserialize($feed->persons);
$personsText = " ";
if(!empty($personsArr)){
$firstItem = json_decode($personsArr[0], true);
$personsText = implode(', ', array_column($firstItem, 'value'));
}
$feed->personsNew = $personsText;
}
$response['success'] = true;
$response['adDetails'] = $adDetails;
echo json_encode($response);

Array element returning "true" instead of value

I have a PHP code that converts a JSON into an array of two elements.
{"object":"card","id":"card_1"}
But when I try to print the both, the first returns the value and the second only the boolean.
echo 'id = ' . $response["id"];
echo 'object = ' .$response["object"];
Getting this:
id = true
object = card
What is wrong?
It seems, that you use json_decode to convert your JSON data to an array. Use next basic example to get your expected data:
<?php
// Input
$json = '{"object":"card","id":"card_1"}';
$array = json_decode($json, true);
// Specific items
echo 'id = '.$array["id"].'<br>';
echo 'object = '.$array["object"].'<br>';
// All items
foreach($array as $key => $value) {
echo $key.": ".$value."<br>";
}
?>
Could you please provide the code you use to convert this JSON into an array ?
This works fine:
$jsonObject = '{"object":"card","id":"card_1"}';
$decodedObject = json_decode($jsonObject);
$object = $decodedObject->object;
$id = $decodedObject->id;
echo "Object: {$object}, ID: {$id}";

PHP: Loop on JSON?

i have the following JSON:
{"Switches":["Auswahl1","Auswahl2","Auswahl3"],"Check_MK":["Auswahl1","Auswahl2","Auswahl3"],"Testgroup":["Auswahl1","Auswahl2","Auswahl3"],"Printer":["Auswahl1","Auswahl2","Auswahl3"],"CAD":["Auswahl1","Auswahl2","Auswahl3"]}
How do i loop each object while using PHP?
My thoughts were the following:
<?php
$jsonfile = file_get_contents('tags.json');
echo $jsonfile . "<br><br>";
$decode = json_decode($jsonfile);
foreach($decode as $key => $value) {
echo $key . $value;
}
?>
Doesn't work..... Also
echo $decode[1];
and
echo $decode[1][1];
doesn't work..
You need to add a second parameter to json_decode()
This parameter returns associative array instead of existing object (if existing).
$decode = json_decode($jsonfile, TRUE);
This will convert your JSON decoded data into associative array.
$jsonfile = file_get_contents('tags.json');
echo $jsonfile . "<br><br>";
$decode = json_decode($jsonfile);
now $decode is equivalent to:
$decode = new stdClass();
$decode->Switches = array();
$decode->Switches[] = "Auswahl1";
$decode->Switches[] = "Auswahl2";
$decode->Switches[] = "Auswahl3";
$decode->Check_MK = array();
...

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

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'];
}
}

Categories