How to parse json in php from url - php

Im new to json, so i gotta ask you a maybe really simple questions.
I've tried searching around but have not found anything I can get to work.
I have called an API and received the data in json.
And now comes my problem parsing it through my php, it "will not find anything."
My code looks like this:
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept: application/vnd.travify.v1+json\r\n"
)
);
$context = stream_context_create($opts);
$url = 'http://oda.ft.dk/api/Sag?$select=titel,Sagskategori/kategori&$expand=Sagskategori';
$output = file_get_contents($url, false, $context);
$string = file_get_contents($url, false, $context);
$result = json_decode($string, true);
$i = -1;
foreach ($result as $data) {
$i++;
echo "#";
echo $i;
echo "<br>";
echo "<b>Test 1:</b>";
echo "<br>";
if(!empty($result[$i]['value']['Sagskategori']['kategori'])){
echo $result[$i]['value']['Sagskategori']['kategori'];
}else{
echo "Intet fundet.";
}
echo "<hr>";
}
The json code can be find here: http://oda.ft.dk/api/Sag?$select=titel,Sagskategori/kategori&$expand=Sagskategori
Can anyone of you see my fail in the code, and get me on the right way :-) ?

Please replace
foreach ($result as $data) {
by
foreach ($result["value"] as $data) {
And now you can iterate to your value array and get all informations from $data
You don't need use $i, $data contains correct $result[$i] value
foreach ($result["value"] as $data) {
echo "#";
echo "<br>";
echo "<b>Test 1:</b>";
echo "<br>";
if(!empty($data['Sagskategori']['kategori'])){
echo $data['Sagskategori']['kategori'];
}else{
echo "Intet fundet.";
}
echo "<hr>";
}

The JSON starts like this:
{
"odata.metadata":"...snip...","value":[
{
So the array is inside the value object.
The correct code should be:
foreach ($result['value'] as $data) {
// snip
if(!empty($result['value'][$i]['Sagskategori']['kategori'])){
echo $result['value'][$i]['Sagskategori']['kategori'];
}
Also, inside the loop, $result['value'][$i]['Sagskategori']['kategori']; is strictly the same as using $data['Sagskategori']['kategori'];.

Related

how to echo fixer.io json php

Hi I'm trying get a json from fixer.io and then for each rates echo it but cant get it to work.
the code are
<?php
function usd(){
echo 'HEJ test';
$fixer_access_key = my_access_key;
$url= 'https://data.fixer.io/api/latest?access_key=' . $fixer_access_key;
echo $url;
$json = file_get_contents($url);
$data = json_decode($json);
echo $url . "<br>";
echo 'printing json foreach <br>';
foreach($data as $obj){
echo '...';
$prefix = $obj;
echo $prefix;
echo '<br>';}
echo 'done printing json foreach';
}
usd(); ?>
and the result are:
https://data.fixer.io/api/latest?access_key=my_fixer_key
printing json foreach
done printing json foreach
instead of
$data = json_decode($json);
use
$data = json_decode($json, true);
This should allow foreacha to works - however you will only see first level of json object keys (not nested ones). The second parameter of json_decode change result from object to array.
You will also need to change foreach - to following: foreach($data as $key => $obj) and inside it echo $obj to echo $key;.
Here is simplified working example.
ALTERNATIVE SOLUTION
If working foreach is not your goal but rather pretty printed json, then instead use following code:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;

Decoding data into HTML

I have a URL that returns JSON data and is constantly being updated. I'm trying to get the contents of this data to show up on my site. Here is JSON file (url)
I only need the contents from the 'images' (pretty far down there) array ... when I try and use just simple php code:
$json_data = file_get_contents($url);
$json = json_decode($str, true);
$result = array();
foreach($json['designs']['images'] as $image); {
$result[] = $image['url'];
}
echo $result;
I just keep returning 'Array' on the browser. If I replace echo with print_r I get this: Array ( [0] => SWZ51F ) which is correct, but i would like it to display in HTML format.
After the loop, $result is an array of all image URLs. You can loop through it to output the html. A basic approach would be :
foreach ($result as $url) {
echo '<img src="' . $url . '"/><br/>';
}
Or use a single loop:
foreach($json['designs']['images'] as $image); {
echo '<img src="' . $image['url'] . '"/><br/>';
}
Try this:
This is for ALL IMAGES URL:
$result = array();
foreach($json['designs']['images'] as $image){
$result[] = $image['url'];
}
var_dump($result);
This is for single IMAGE URL:
$result=$json['designs']['images'][0]['url'];
echo $result;

How to print jSON values with loop

I am using the following code to print the output of the jSON response but when I try to print
echo $obj->HotelListResponse->customerSessionId; // This is working.
echo $obj->HotelListResponse->HotelList->HotelSummary->name; // This is not working.
When the response contains only one node then its printing perfectly but when there are multiple nodes with same name then its not printing. I tried using foreach just like the below. I also tried using while loop but still I am unable to print the list of hotel names.
My jSON decoded output is like http://pastebin.com/Fr21DkEk
Total code:
$url = "https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55505&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_AU&currencyCode=AUD&xml=<HotelListRequest><city>Brisbane</city><stateProvinceCode>QLD</stateProvinceCode><countryCode>AU</countryCode><arrivalDate>10/16/2014</arrivalDate><departureDate>10/18/2014</departureDate><RoomGroup><Room><numberOfAdults>2</numberOfAdults></Room></RoomGroup><numberOfResults>25</numberOfResults></HotelListRequest>";
$json = file_get_contents($url);
$obj = json_decode($json);
foreach($obj as $val) {
echo $val->HotelListResponse->HotelList->HotelSummary->name;
}
Try this
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
echo $val->name . '<br/>';
}
HotelSummary is an array:
echo $val->HotelListResponse->HotelList->HotelSummary[0]->name;
If you want all of the hotel summaries:
foreach($obj as $val) {
foreach($val->HotelListResponse->HotelList->HotelSummary as $sum) {
echo $sum->name;
}
}
Yes you can directly access them inside the foreach. Like this:
foreach($obj->HotelListResponse->HotelList->HotelSummary as $val) {
// ^^
// since you're interested on just names, you can point it directly on that object, then each of that batch is in `$val`
echo $val->name . '<br/>';
}
// or start from the parent
foreach($obj as $values) {
$customerSessionId = $values->customerSessionId;
echo $customerSessionId . '<hr/>';
$hotelList = $values->HotelList;
foreach($hotelList->HotelSummary as $hotelsummary) {
echo $hotelsummary->name . '<br/>';
}
}

Data from JSON to php?

I need help with fetching only attraction data,
i have this php script on my website:
<?php $json_string = 'http://framecreators.nl/efteling/data.php'; $jsondata file_get_content($json_string); $json_o=json_decode(utf8_encode($data)); $attractie = $json_o['Id']['Type']; echo $attractie ?>
and this json data:
http://framecreators.nl/efteling/data.php
I need to convert only a Id and type, ff somebody can help me.
To access the data you're looking for, you'll need to do something like this:
foreach ($json_o['AttractionInfo'] as $a) {
echo $a['Id']; //or whatever you're planning to do with this data
ech0 $a['Type'];
}
<?php
$json_data = file_get_contents('http://framecreators.nl/efteling/data.php');
$data = json_decode($json_data);
$array = [];
foreach($data->AttractionInfo as $item) {
$array['id'][] = $item->Id;
$array['type'][] = $item->Type;
}
echo "<pre>";
print_r($array);
echo "</pre>";
$url = "http://framecreators.nl/efteling/data.php";
$content = file_get_contents($url);
$data = json_decode($content,TRUE);
$array = $data['AttractionInfo'];
foreach($array as $r)
{
echo "ID->".$r['Id'];
echo '';
echo "Type->".$r['Type'];
echo '';
}
$url = "http://framecreators.nl/efteling/data.php";
$content = file_get_contents($url);
$data = json_decode($content,TRUE);
$array = $data['AttractionInfo'];
if(is_array($array))
{
foreach($array as $r)
{
echo $r['Id'];
echo $r['Type'];
}
}

json and PHP parse

Why i can't get out the values from the json file with PHP?
I get zero values? Have tried for hours.
<?php
$json_string = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=44';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
print_r($data);
echo "<br><br><br><br>";
foreach ($data as $recenttrades) {
echo "VALUES('{$recenttrades->quantity}', '{$recenttrades->price}' ";
}
?>
Update: but can't get the value from primaryname and primarycode.
I have tried this:
$json_string = 'http://pubapi.cryptsy.com/api.php?method=marketdatav2';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
//print_r($data);
foreach ($data["market"] as $markets) {
echo "Primary code: <strong>{$markets['primarycode']}</strong><br>";
foreach($markets as $market) {
foreach($market as $attributes) {
foreach($attributes["recenttrades"] as $recenttrade) {
echo "quantity: " . $recenttrade['quantity'] .", price: " . $recenttrade['price'] . "<br>";
}
}
}
}
Others have mentioned that you're dealing with nested arrays, not objects. Along with pointing out the issue of being nested rather deeply, I would suggest digging down with foreach (I will probably be crucified for this):
<?php
$json_string = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=44';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
//print_r($data);
echo "<br><br><br><br>";
foreach ($data as $markets) {
foreach($markets as $market) {
foreach($market as $attributes) {
foreach($attributes["recenttrades"] as $recenttrade) {
//echo "<pre>";
//print_r($recenttrade);
//echo "</pre>";
echo "VALUES('{quantity: " . $recenttrade['quantity'] ."}', 'price: {" . $recenttrade['price'] . "}')";
}
}
}
}
?>
This will ensure that you grab every recentrades item at this level of the array. This way you are prepared for other markets to be added to the API and your code isn't locked into searching only in the item named "FST".
recenttrades is nested pretty deeply in that array. Try
foreach ($data['return']['markets']['FST']['recenttrades'] as $recenttrades) {
recenttrades is several levels nested, so simply doing foreach($data as $recenttrades) is not sufficient.
You need to do:
$recentTrades = $data['return']['markets']['FST']['recenttrades'];
foreach($recentTrades as $recentTrade) {
...
}
recenttrades is nested deeply and you're asking for arrays, not objects. This seems to work:
foreach ($data['return']['markets']['FST']['recenttrades'] as $recenttrades) {
echo "VALUES('{$recenttrades['quantity']}', '{$recenttrades['price']}' ";
}
In response to your update, where you want to loop over markets, try this:
foreach ($data['return']['markets'] as $market) {
echo "Primary code: <strong>{$market['primarycode']}</strong><br>";
foreach ($market["recenttrades"] as $recenttrade) {
echo "quantity: " . $recenttrade['quantity'] .", price: " . $recenttrade['price'] . "<br>";
}
}

Categories