working with JSON in php - php

I have a problem echo'ing data from a JSON file:
<?php
$url = file_get_contents("http://api.erpk.org/citizen/profile/3121752.json?key=Yn3AsG80");
$json = file_get_contents($url);
$data = json_decode($json, true);
echo "<pre>"; var_dump($data); echo"</pre>";
?>
the above is my php file i am using which outputs the JSON as shown below:
{
"id": 3121752,
"name": "SnowderBlazer",
"birth": "2010-04-10",
"avatar": "http://static.erepublik.net/uploads/avatars/Citizens/2010/04/10/4bb9a72cc291faaaf7af8e78ed0a8509_100x100.jpg",
"online": false,
"ban": null,
"alive": true,
"level": 97,
"experience": 360391,
"strength": 42859.62,
"rank": {
"points": 437120237,
"level": 64,
"image": "http://www.erepublik.com/images/modules/ranks/god_of_war_2.png",
"name": "God of War**"
},
"elite_citizen": false,
"national_rank": 1,
"residence": {
"country": {
"id": 65,
"name": "Serbia",
"code": "RS"
},
"region": {
"id": 198,
"name": "Midi-Pyrenees"
}
},
"citizenship": {
"id": 65,
"name": "Serbia",
"code": "RS"
},
"about": "Voters Club Moderator\ncatch me on #voters #Rizon\nIRC Nick : Snowderblazer OR Snowderblazer[BNC]\norder herehttp://erepublik-market.com/voters/newOrder.html?adp=1549866\n[ident:9vrwQZB9]",
"party": {
"id": 2479,
"name": "Ujedinjena eSrbija",
"role": "Party Member"
},
"army": {
"id": 1980,
"name": "Legija Stranaca Elite",
"role": "Commander",
"created_at": "2012-05-26",
"avatar": "http://static.erepublik.net/uploads/avatars/Groups/2012/05/26/f80bf05527157a8c2a7bb63b22f49aaa_medium.jpg",
"rank": "Commander"
},
"newspaper": {
"id": 241367,
"role": "Press director",
"name": "M.A.D.S News"
},
"top_damage": {
"damage": 215238312,
"date": "2013-05-16",
"message": "Achieved while successfully defending Basilicata against Italy on day 2,004"
},
"true_patriot": {
"damage": 3021790429,
"since": "2012-04-26"
},
"medals": {
"battle_hero": 248,
"campaign_hero": 98,
"congress_member": 9,
"country_president": 0,
"hard_worker": 36,
"media_mogul": 5,
"mercenary": 1,
"resistance_hero": 2,
"society_builder": 0,
"super_soldier": 171,
"top_fighter": 3,
"true_patriot": 43
},
"hit": 14924
}
my problem is just that it loads all data at once, and i only want to echo each
i have no experience with JSON so i don't knwo the variables to echo
the via the JSON you can visit
JSON Version : http://api.erpk.org/citizen/profile/3121752.json?key=Yn3AsG80
XML Version : http://api.erpk.org/citizen/profile/3121752.xml?key=Yn3AsG80
What I want to achieve is the following:
Load the JSON or XML without the output so that I can use the ECHO to put he data where i want it to show in the PHP file;
ECHO each of the JSON or XML data.
Everytime I try I get an error that says its a non-object

json_decode($json, true) returns a plain array, it's not specific to json and you can access its elements just like an other array:
$data = json_decode($json, true);
var_dump($data['name']);
If you want to get objects instead, remove the second argument:
$data = json_decode($json);
var_dump($data->name);

You're misusing file_get_contents, so I'm guessing that's your problem. To fetch data from that URL just your first line with this one:
$url = 'http://api.erpk.org/citizen/profile/3121752.json?key=Yn3AsG80';
Anyway, here's a code snippet to echo a short profile given your JSON dataset.
It shows you how to access 1st level fields like name and birth, 2nd level as rank\level and rank\name and finally a dynamic set of fields like medals.
<?php
$json = '{"id":3121752,"name":"SnowderBlazer","birth":"2010-04-10","avatar":"http://static.erepublik.net/uploads/avatars/Citizens/2010/04/10/4bb9a72cc291faaaf7af8e78ed0a8509_100x100.jpg","online":false,"ban":null,"alive":true,"level":97,"experience":360391,"strength":42859.62,"rank":{"points":437120237,"level":64,"image":"http://www.erepublik.com/images/modules/ranks/god_of_war_2.png","name":"God of War**"},"elite_citizen":false,"national_rank":1,"residence":{"country":{"id":65,"name":"Serbia","code":"RS"},"region":{"id":198,"name":"Midi-Pyrenees"}},"citizenship":{"id":65,"name":"Serbia","code":"RS"},"about":"Voters Club Moderator\ncatch me on #voters #Rizon\nIRC Nick : Snowderblazer OR Snowderblazer[BNC]\norder herehttp://erepublik-market.com/voters/newOrder.html?adp=1549866\n[ident:9vrwQZB9]","party":{"id":2479,"name":"Ujedinjena eSrbija","role":"Party Member"},"army":{"id":1980,"name":"Legija Stranaca Elite","role":"Commander","created_at":"2012-05-26","avatar":"http://static.erepublik.net/uploads/avatars/Groups/2012/05/26/f80bf05527157a8c2a7bb63b22f49aaa_medium.jpg","rank":"Commander"},"newspaper":{"id":241367,"role":"Press director","name":"M.A.D.S News"},"top_damage":{"damage":215238312,"date":"2013-05-16","message":"Achieved while successfully defending Basilicata against Italy on day 2,004"},"true_patriot":{"damage":3021790429,"since":"2012-04-26"},"medals":{"battle_hero":248,"campaign_hero":98,"congress_member":9,"country_president":0,"hard_worker":36,"media_mogul":5,"mercenary":1,"resistance_hero":2,"society_builder":0,"super_soldier":171,"top_fighter":3,"true_patriot":43},"hit":14924}';
$data = json_decode($json, true);
echo "Name: {$data['name']}\n";
echo "Date of birth: {$data['birth']}\n\n";
echo "Level: {$data['rank']['level']}\n";
echo "Rank: {$data['rank']['name']}\n\n";
echo "Medals\n";
foreach ($data['medals'] as $medalName => $number) {
echo ucfirst(str_replace('_', ' ', $medalName)) . ": {$number}\n";
}
Output
Name: SnowderBlazer
Date of birth: 2010-04-10
Level: 64
Rank: God of War**
Medals
Battle hero: 248
Campaign hero: 98
Congress member: 9
Country president: 0
Hard worker: 36
Media mogul: 5
Mercenary: 1
Resistance hero: 2
Society builder: 0
Super soldier: 171
Top fighter: 3
True patriot: 43

Related

Display JSON Response specific keys/values using PHP

I want to display specific keys and values from the following JSON Response I am using API to fetch the JSON values:
[
{
"tracking_data": {
"track_status": 1,
"shipment_status": 7,
"shipment_track": [
{
"id": 42719783,
"pickup_date": "2020-07-20 19:07:00",
"delivered_date": "2020-07-22 11:36:00",
"weight": "0.15",
"packages": 1,
}
],
"shipment_track_activities": [
{
"date": "2020-07-22 11:36:00",
"status": "DLVD",
"activity": "Delivered Shipment Delivered by SR: VasudevDengi, MobileNo: 7999869145, DeliveryDate: 2020-07-22 11:36:30, Receiver Name: Suman Rajnod ",
"location": "IDR/RJN, Indore, MADHYA PRADESH"
},
{
"date": "2020-07-22 10:21:00",
"status": "OFD",
"activity": "Out for Delivery Out for delivery: 104688-VasudevDengi-PDS20204102119104688-FromMob",
"location": "IDR/RJN, Indore, MADHYA PRADESH"
},
{
"date": "2020-07-22 08:09:00",
"status": "RAD",
"activity": "Reached at Destination InScan ( Shipment Auto Bagout )",
"location": "IDR/RJN, Indore, MADHYA PRADESH"
},
{
"date": "2020-07-21 07:07:00",
"status": "IT",
"activity": "InTransit Shipment added in ParentBagNo: NXBB024886",
"location": "IDR/IDR, Indore, MADHYA PRADESH"
}
]
I am trying to display with this php code but it's giving blank screen, also the JSON values (I mentioned above) are assigned to $response variable.
$js = json_decode($response, true);
foreach($js as $return){
echo $return['tracking_data']['track_status'];
} ?>
Addition - I can display track_status value following solution provided #Aashishgaba thanks,
Can you also guide me to display data like "pickup_date" and "shipment_track_activities" as you can see there is multiple data based on dates.
$js = json_decode($response, true);
foreach($js as $return){
echo $return['tracking_data']['track_status'];
foreach($return['tracking_data']['shipment_track'] as $st){
echo $st['pickup_date'];
}
foreach($return['tracking_data']['shipment_track_activities'] as
$sta){
echo $sta['date'];
echo $sta['status'];
}
} ?>

Getting data from nested arrays in json with php

I have my json from a url feed. Here's a sample below. I'm not doing the foreach loop correctly is the problem
{
"useLive": true,
"models": [
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",
"id": 5293074,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu7",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model1",
"languages": ["en"],
"stripScore": 998.5,
"token": "93021860dbebd5ba27e604f6b4b93754"
},
{
"snapshotUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",
"id": 6492104,
"country": "",
"gender": "female",
"isNew": false,
"previewUrl": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-full",
"previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-big",
"previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-small",
"broadcastGender": "female",
"snapshotServer": "eu8",
"tags": ["autoTagPopular","keyword","keyword2"],
"topBestPlace": 0,
"username": "model2",
"languages": [],
"stripScore": 997.25,
"token": "2c6ee95270f6faf76cd33321732136e3"
}
],
"ttl": 15,
"tagType": "F+T",
"tagName": "Featured",
"defaultTags": [
{
"name": "whatever1",
"url": "/tags/whatever1"
},
{
"name": "whatever2",
"url": "/tags/whatever2"
},
{
"name": "whatever3",
"url": "/tags/whatever3"
}
],
"serverTime": "2018-09-26T14:23:00Z"
}
Here's my php code so far. I've tried quite a few different things. I normally use xml feeds which seem to be easy for me to setup for what I need. I'm not sure what I'm missing here.
$url = 'https://whatever.com/api/external/v4/widget?userId=whatever&tag=featured'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$performers = json_decode($data, true); // decode the JSON feed
foreach ($performers as $performer) {
$info = $performer[0]["username"];
echo $info;
}
I'm only getting the first username and then error messages.
Warning: Illegal string offset 'username' in /whatever
Can anyone help with this?
You should use $performers['models'] array in foreach and then get username it will work fine try the following code
$performers = json_decode($data, true);
if(isset($performers['models'])){
foreach ($performers['models'] as $performer) {
$info = (isset($performer["username"])) ? $performer["username"] : '';
echo $info;
echo "<br>";
}
}
Output
model1
model2

Get JSon child with PHP echo from an API

Okay so bascially I have this structure as JSon from an API:
{
"tag": "8L9L9GL",
"name": "Jo͛hͥn̽",
"trophies": 5338,
"rank": 291,
"arena": {
"name": "Master II",
"arena": "League 5",
"arenaID": 17,
"trophyLimit": 5200
},
"clan": {
"tag": "2U2GGQJ",
"name": "Reddit Bravo",
"role": "coLeader",
"donations": 0,
"donationsReceived": 0,
"donationsDelta": 0,
"badge": {
"name": "A_Char_Rocket_02",
"category": "03_Royale",
"id": 16000167,
"image": "https://cr-api.github.io/cr-api-assets/badges/A_Char_Rocket_02.png"
}
},
I'm trying to get the Clan -> Name but it isn't working with this code in PHP:
echo "<p style='font-size:75;'>".$json->clan['name']."</p>";
How could I make it work?
Try this:
$json->clan->name
<?php
$json = '{
"tag": "8L9L9GL",
"name": "Jo͛hͥn̽",
"trophies": 5338,
"rank": 291,
"arena": {
"name": "Master II",
"arena": "League 5",
"arenaID": 17,
"trophyLimit": 5200
},
"clan": {
"tag": "2U2GGQJ",
"name": "Reddit Bravo",
"role": "coLeader",
"donations": 0,
"donationsReceived": 0,
"donationsDelta": 0,
"badge": {
"name": "A_Char_Rocket_02",
"category": "03_Royale",
"id": 16000167,
"image": "https://cr-api.github.io/cr-api-assets/badges/A_Char_Rocket_02.png"
}
}
}';
$json = json_decode($json);
echo $json->clan->name;
// Reddit Bravo
If you want to use $json['clan']['name']; then you have to set the assoc param like:
$json = json_decode($json, true);
echo $json['clan']['name'];
// Reddit Bravo
Depending on your particular call to json_decode(), if you've used...
$json = json_decode($jsonData,true);
then use
echo "<p style='font-size:75;'>".$json['clan']['name']."</p>";
Else if you've used...
$json = json_decode($jsonData);
then use
echo "<p style='font-size:75;'>".$json->clan->name."</p>";
If using the first call, then you create an associative array and so use array access method. If you don't pass true as the second parameter, this creates the structure as objects and so use the second method of access.
You will have to json_decode the same and use it.
Following is the piece of code
echo json_decode($json)->clan->name;
Stitch it into your HTML as
echo "<p style='font-size:75;'>".json_decode($json)->clan->name."</p>";
Tested this snippet. Should work for you too.

Impossible to fetch data from a json file into php variable

I'm using Giscloud's REST API to grab a json with some info that i need for my web app. The problem is that it seems impossible that I can fetch and/or decode any data from that json using the corresponding php functions. I think it has something to do with the way the json file is structured.
This is the json file (some fields edited):
{
"type": "maps",
"total": 3,
"page": 1,
"data": [
{
"id": "edited",
"name": "Mapa de Mantención en Linea",
"owner": "edited",
"epsg": "900913",
"active": "1",
"copyright": "",
"proj4": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs",
"units": "meter",
"maxzoom": "0",
"mobileacess": "f",
"bgcolor": "#417893",
"wmsaccess": null,
"modified": 1483563460,
"accessed": 1483563460,
"created": 1483021672,
"description": "",
"maptype": null,
"assets": null,
"rating": "0",
"units_proj4": "meter",
"visited": "31",
"resource_id": "6102219",
"measure_unit": "meter",
"share": "f",
"bounds": " {\"xmin\":-8027875.3326789,\"xmax\":-7742459.4690621,\"ymin\":-4065685.5344885,\"ymax\":-3929474.7500843}"
},
{
"id": "edited",
"name": "Mapa de Operaciones",
"owner": "edited",
"epsg": "900913",
"active": "1",
"copyright": "",
"proj4": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs",
"units": "meter",
"maxzoom": "0",
"mobileacess": "f",
"bgcolor": "#417893",
"wmsaccess": null,
"modified": 1483563473,
"accessed": 1483563473,
"created": 1483021672,
"description": "",
"maptype": null,
"assets": null,
"rating": "0",
"units_proj4": "meter",
"visited": "45",
"resource_id": "6102603",
"measure_unit": "meter",
"share": "f",
"bounds": "{\"xmin\":-8027263.8364526,\"xmax\":-7741847.9728358,\"ymin\":-4075469.474109,\"ymax\":-3939258.6897048}"
},
{
"id": "edited",
"name": "Mapa M&IC",
"owner": "edited",
"epsg": "900913",
"active": "1",
"copyright": "",
"proj4": "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=#null +no_defs",
"units": "meter",
"maxzoom": "0",
"mobileacess": "f",
"bgcolor": "#417893",
"wmsaccess": null,
"modified": 1483563449,
"accessed": 1483563449,
"created": 1483021672,
"description": "",
"maptype": null,
"assets": null,
"rating": "0",
"units_proj4": "meter",
"visited": "35",
"resource_id": "6102604",
"measure_unit": "meter",
"share": "f",
"bounds": "{\"xmin\":-8028181.080792,\"xmax\":-7742765.2171752,\"ymin\":-4074552.2297696,\"ymax\":-3938341.4453654}"
}
]
}
These are the different ways that i've tried to decode this json and put it into a variable.
$json = curl_exec($ch);
// Number 1
$data = var_dump(json_decode($json));
echo $data['data'][0]['id'];
exit;
// Number 1 returns
object(stdClass)[21]
public 'code' => string 'FATAL' (length=5)
public 'msg' => string 'Internal error' (length=14)
// Number 2
$data = json_decode($json,true);
echo $data['data'][0]['id'];
// Number 2 returns
PHP Undefined index: data
I've tried several other similar functions, like print_r. Or change some values there and here, but nothing has worked.
I would appreciate a lot some help on this!
Some extra info:
There's no problem with curl. It executes correctly.
Yes, the server answers with a json file.
UPDATE
Using json_last_error() (no need of parameters) I was able to debbug. The function returns an int depending of the type of error. Mine was 0meaning that there's no error.
I think I ran out of ideas for this.
Loose the var_dump() thats just for debugging and it is stoppping the json_decode() from returning a PHP Object from the json_decode().
Then use the correct object syntax to address the object
$json = curl_exec($ch);
$data = json_decode($json);
// debug code
if ( json_last_error() > 0) {
echo json_last_error_msg();
} else
// this should print the data structure
print_r($data);
}
// end debug code
echo $data->data[0]->id;
If you want all the id's from all the occurances you can do
$json = curl_exec($ch);
$data = json_decode($json);
foreach ($data->data as $idx => $obj ){
echo "Occurance $idx = " . $obj->id;
}
Object syntax:
$json = curl_exec($ch);
$json_data = json_decode($json);
foreach ( $json_data->data as $data_item){
echo '<p>ID: ' . $data_item->id . ' -- Name: ' . $data_item->name . '</p>';
}
Array Syntax:
Get the data as an associated array by adding a second parameter TRUE to json_decode() php docs
$json = curl_exec($ch);
$data_array = json_decode($json, true);
foreach ( $data_array['data'] as $item){
echo '<p>ID: ' . $item['id'] . ' -- Name: ' . $item['name'] . '</p>';
}
i dont preferable to use cURL In this situation , you can use
file_get_contents
so here is a simple code
$userdata = json_decode(file_get_contents("JSON_URL_GOES_HERE"), true)
$u_ID = $userdata['data'][0]['id'];
and so on
see :file_get_contents

Insert JSON values in MYSQL using PHP

I've this JSON string:
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
}
}';
I'd like to print every single entry on a webpage using php and then save these entries on a mysql db.
In the db there is already a "code", "name" and "link" field..
This is what I've tried without luck (to print the stuff on a page):
$obj = json_decode($json,true);
echo ($obj["bigprodlist"]["prods"][0]["name"]);
Thank you very much for the help
First, fix your JSON missing end bracket that makes JSON decoding fail (add the ] after the prods data ), then expand your echo statement with some foreach loops to get the data printed. This is only a simple example to get you on the right track:
foreach ($obj["bigprodlist"]["prods"] as $p):
echo "<div>";
foreach ($p as $name=>$value):
echo "<span>".$name.": ".$value."</span>";
endforeach;
echo "</div>";
endforeach;
You can then use the same loop procedure to get the data into your DB.
You need to use json_last_error(); http://no1.php.net/manual/en/function.json-last-error.php
Debugging:
$obj = json_decode($json,true);
var_dump($obj, json_last_error());
You are missing a ] :
$json = '{
"bigprodlist": {
"prods": [
{
"code": 55,
"name": "Comix Book",
"link": "weblink"
},
{
"code": 85,
"name": "IT Book",
"link": "weblink"
},
{
"code": 95,
"name": "Manga Book",
"link": "weblink"
}
] //missing!
}
}';
Where did you get json output?
It's invalid:
Parse error on line 18:
... } } }
----------------------^
Expecting ',', ']'
Check your json at http://jsonlint.com/

Categories