PHP get json data with json_decode - php

I'm new to PHP and try to echo out some data from json, but I got stucked in this.
It shows non of the data, but the data is there. The var_dump() shows it to me.
Probably I don't use the array correctly, but I can't find what's wrong. I've this code,
I request some data which I gathered with knockout.js
Knockout gives me a json (as show below)
$json = $_REQUEST[seats];
echo 'requested data raw '. "<br>".$json;
$data = json_decode($json, true);
echo "<br>".'var_dump '. "<br>";
var_dump($data);
foreach ($data as $optie ) {
echo "name = " . $optie->name . "<br>";
echo "optie = " . $optie->optieName . "<br>";
echo "prijs = " . $optie->prijs . "<br>";
}
This is my JSON:
[
{
"name": "Naam 1",
"optie": {
"optieName": "Make_up",
"prijs": 9.95
},
"PrijsFormated": "Euro: 9.95"
},
{
"name": "Naam 2",
"optie": {
"optieName": "Handverzorging",
"prijs": 12.95
},
"PrijsFormated": "Euro: 12.95"
}
]

You should use such loop:
foreach ($data as $optie ) {
echo "name = " . $optie['name'] . "<br>";
echo "optie = " . $optie['optie']['optieName'] . "<br>";
echo "prijs = " . $optie['optie']['prijs']. "<br>";
}
Because using json_decode() with second parameter as true you have created associative array - documentation.
If you would like to access data as object, you should use:
$data = json_decode($json);
instead of
$data = json_decode($json, true);
and then you should use the following loop:
foreach ($data as $optie ) {
echo "name = " . $optie->name . "<br>";
echo "optie = " . $optie->optie->optieName . "<br>";
echo "prijs = " . $optie->optie->prijs. "<br>";
}

Related

How to work with this JSON, including array

I tried to work with basic, few param. JSON code and there wasn't any problem with that.
BUT now i need work with this "advanced" JSON and I am kinda lost
{
"code":"success",
"username":"x",
"nodes":[
{
"id":"68",
"time":987
},
{
"id":"69",
"time":987
}
]
}
When i tried to get the values into PHP variable with previou code, I wasn't able to get ID and TIME, CODE and SUCCESS isn't problem.
PHP code I used:
$url = "example.com";
$url = str_replace(" ","%20",$url);
$json = #file_get_contents($url);
$details = json_decode($json, TRUE);
// print_r($details);
echo $details[code];
Thank you guys!
<?php
$url = "example.com";
$url = str_replace(" ","%20",$url);
$json = #file_get_contents($url);
$details = json_decode($json, TRUE);
if (is_array($details['nodes'])) {
echo "node count: " . count($details['nodes']) . "<br />";
foreach ($details['nodes'] as $node) {
echo "id: " . $node['id'] . "<br />";
echo "time: " . $node['time'] . "<br />";
}
}

How do I get one json value value each?

in this my php code
echo $_POST[result];
in this my php result
{
"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}
I want to print out each value one by one. What should I do?
json_decode Parsing JSON
<?php
$str = '{"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}';
$arr = json_decode($str, true);
echo $arr['err_cd'] . PHP_EOL;
echo $arr['result_msg'] . PHP_EOL;
echo $arr['store_id'] . PHP_EOL;
echo $arr['status'] . PHP_EOL;
// ......
// Circulates each value in the array
foreach ($arr as $item) {
echo $item . PHP_EOL;
}

How to make foreach work with this PHP script - GET API

I'm working on a script that will retrieve API information of the 'near earth objects' from NASA's website. User selects date, api grabs the information and displays it. How do I fix the foreach in this script? would appreciate some help with this.
$jsonAsteroids = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($jsonAsteroids, true);
echo "<h4>Retrieving the first element (i.e. \"links\") of the JSON structure</h4>";
var_dump( $data["links"]);
echo "<h4>Retrieving the first element (i.e. \"next\") inside the \"links\" element</h4>";
echo( $data["links"]["next"]);
You were very close. Your main issue was that you used json_decode(..., true); which gives you an array, but then used the object->property syntax instead of object['property']. My suggestion is to use json_decode without the 2nd argument in this case.
Finally, your 2nd foreach was malformed.
<?php
$result = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($result);
foreach ($data->near_earth_objects as $date => $objects) {
echo "<p>" . count($objects) . " objects detected on $date</p>";
echo "<ol>";
foreach ($objects as $object) {
echo "<li>" . $object->name . " <a href='" . $object->nasa_jpl_url . "'>" . $object->nasa_jpl_url . "</a><br>";
echo "Diameter of the object: " . $object->estimated_diameter->meters->estimated_diameter_min . "-" . $object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($object->close_approach_data as $close_approach) {
echo "<li>Close approach: " . $close_approach->close_approach_date . " traveling at a velocity of " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul>";
}
echo "</ol>";
}

PHP For Each value in object [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 4 years ago.
im working on a project but I ran into a problem :(
I looked on the internet for like 2-3 hours and cannot find the way how to do it...
I retrieve this JSON from my database:
{
"articles": {
"1": {"discription":"Transport", "tax":"21", "price":"234"
},
"2": {"discription":"Opslag", "tax":"19", "price":"19"}
}
}
What I want to do next is retrieve the description,tax & Price from each object, how to do this with a for each loop on the most efficient way?
Thanks!
You can use following code snippet to get value of mentioned keys-
<?php
$str = '{
"articles": {
"1": {"discription":"Transport", "tax":"21", "price":"234"
},
"2": {"discription":"Opslag", "tax":"19", "price":"19"}
}
}';
//convert json to array
$jsonToArray = json_decode($str, true);
foreach ($jsonToArray['articles'] as $value) {
echo $value['discription'] . ' ' . $value['tax'] . ' ' . $value['price'] . PHP_EOL;
}
if you want to access those keys with object then you can proceed with following code snippet-
<?php
$str = '{
"articles": {
"1": {"discription":"Transport", "tax":"21", "price":"234"
},
"2": {"discription":"Opslag", "tax":"19", "price":"19"}
}
}';
//convert json to object
$jsonToObject = json_decode($str);
foreach ($jsonToObject->articles as $value) {
echo $value->discription . ' ' . $value->tax . ' ' . $value->price . PHP_EOL;
}
You are free to make changes in the echo statement that suits your requirement.
Checkout my all the technical post.
$array = json_decode($json_string);
for($i = 0; $i<sizeof($array); $i++) {
echo $array[$i]['description'];
echo $array[$i]['tax'];
echo $array[$i]['price'];
}
You are looking for the json_decode function before you do that, here's an example:
$jsonDecoded = json_decode($jsonInput);
foreach ($jsonDecoded->articles as $item) {
echo $item->discription . "<br>";
echo $item->tax . "<br>";
echo $item->price . "<br>";
}

Read xml response using php

I have a Api response in XML format.How can I get gps_x and gps_y for both elements.
$url="http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";
$xmlinfo = simplexml_load_file($url);
print_r($xmlinfo);
echo $xmlinfo['gps_x']; // outputs nothing
echo $xmlinfo -> gps_x; // outputs nothing
How can I get gps_x and gps_y from above response?
I did this by getting the content from url then converting to json using exceptions handling and get the data from decoded json:
<?php
$myXMLData = file_get_contents("http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo");
$simpleXml = simplexml_load_string($myXMLData) or die("Error: Cannot create encode data to xml object");
$jsondata = json_encode($simpleXml) or die("Error: Cannot encode record to json");
$data = json_decode($jsondata, true);
$in = $data['items']['item'];
foreach ($in as $key => $value) {
echo "ID= " . $in[$key]['id'] . ", GPS-x = " . $in[$key]['gps_x'] . ", GPS-y = " . $in[$key]['gps_x'];
echo "<br/>";
}
?>
OUTPUT
ID= 2354292, GPS-x = 36.1065000000, GPS-y = 36.1065000000
ID= 2431066, GPS-x = 36.0949905151, GPS-y = 36.0949905151
If you want to take the data from XML directly:
<?php
$myXMLData = file_get_contents("http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo");
$simpleXml = simplexml_load_string($myXMLData) or die("Error: Cannot create encode data to xml object");
$in = $simpleXml->items->item;
foreach ($in as $key) {
echo "ID= " . $key->id;
echo ", GPS-x = " . $key->gps_x;
echo ", GPS-y = " . $key->gps_y . "<br/>";
}
?>
OUTPUT
ID= 2354292, GPS-x = 36.1065000000, GPS-y = 28.0684000000
ID= 2431066, GPS-x = 36.0949905151, GPS-y = 28.0860328674
Looking at the print_r() output, it show that the gps_x & gps_y are part of an item and not directly under the xmlinfo object.
Here is the code that will do the job:
$url = "http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";
$xmlinfo = simplexml_load_file($url);
if ($xmlinfo->items && $xmlinfo->items->item) {
$item = $xmlinfo->items->item;
print $item->gps_x . "\n";
print $item->gps_y . "\n";
}
$url="http://www.tixik.com/api/nearby?lat=36.106121163930377&lng=28.07762145996093&limit=2&key=demo";
$xmlinfo = simplexml_load_file($url);
foreach ($xmlinfo->items->item as $item) {
//echo "<pre>";print_r($item);
echo "<br />". $item->gps_x;
echo "<br />". $item->gps_y;
}

Categories