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'];
}
} ?>
Related
I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.
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
I'm trying to use JSON in PHP and I got stucked. I'm new in this, please, if you can help me with that.
I want to display content from "list" from the code below (For example list, name and/or frags).
{
"status": true,
"hostname": "{IP}",
"port": {PORT},
"queryPort": {PORT},
"name": "Cod2 Server",
"map": "mp_genesisarc",
"secured": true,
"password_protected": false,
"version": "1.3",
"protocol": "udp",
"players": {
"online": 1,
"max": "28",
"list": [
{
"frags": "1",
"ping": "54",
"name": "Mr Anderson"
}
]
},
"cached": false
}
This is the code I use (Doesn't work):
<?php
$serverip = "localhost";
$info = json_decode( file_get_contents( 'https://use.gameapis.net/cod2/query/info/000.000.00.0:0000'.$serverip ), true );
if(!$info['status']) {
echo 'Offline';
} else {
echo $info['players']['list']['name'];
}
?>
Thanks in advance,
Jim.
$info['players']['list'][0]['name']
This will get you desired element. Try outputting $info next time to find this error yourself.
Try using a foreach loop. It's cleaner when iterating an array.
<?php
$serverip = "localhost";
$info = json_decode( file_get_contents( 'https://use.gameapis.net/cod2/query/info/000.000.00.0:0000'.$serverip ), true );
if(!$info['status']) {
echo 'Offline';
}
else {
foreach ($info['players']['list'] as $player) {
echo $player['name'];
}
}
?>
list will you number of online users records so there may be single or multiple users so you have to go through the loop and can display all the records available in the list. Add for loop to your code instead of displaying single record with index.
if(count($info['players']['list']) > 0){
for($cnt = 0; $cnt < count($info['players']['list']); $cnt++){
echo $info['players']['list'][$cnt]['name'];
}
} else {
echo "Write your message";
}
Took the following array (I had to change few things) and go here . Paste the array at the left side, then press the right arrow and see at the right side the analysis of your array. Open the tree view and you will realize that there is a 0 index in the list. So you can not access what you want by doing echo $info['players']['list']['name']; but you need to apply the index 0 of the list echo $info['players']['list'][0]['name'];
[{
"status": true,
"hostname": "{IP}",
"port": 555,
"queryPort": 555,
"name": "Cod2 Server",
"map": "mp_genesisarc",
"secured": true,
"password_protected": false,
"version": "1.3",
"protocol": "udp",
"players": {
"online": 1,
"max": "28",
"list": [
{
"frags": "1",
"ping": "54",
"name": "Mr Anderson"
}
]
},
"cached": false
}]
If you paste your json string into https://jsonlint.com/ and click Validate JSON, you will see that you have a couple of syntax errors; namely the values for port and queryPort.
When they are corrected, you should have something like this:
{
"status": true,
"hostname": "{IP}",
"port": "{PORT}",
"queryPort": "{PORT}",
"name": "Cod2 Server",
"map": "mp_genesisarc",
"secured": true,
"password_protected": false,
"version": "1.3",
"protocol": "udp",
"players": {
"online": 1,
"max": "28",
"list": [{
"frags": "1",
"ping": "54",
"name": "Mr Anderson"
}]
},
"cached": false
}
Now that the json is fixed, you can convert it to an array for simple processing.
Code: (Demo)
$serverip="localhost";
$array=json_decode(file_get_contents( 'https://use.gameapis.net/cod2/query/info/000.000.00.0:0000'.$serverip),true);
if(!isset($array['status']) || $array['status']===false){
echo 'Offline';
}else{
foreach($array['players']['list'] as $players){
echo "<div>Name: {$players['name']}, Frags: {$players['frags']}, Ping: {$players['ping']}</div>\n";
}
}
foreach() is a better/cleaner practice than resorting to for() which will unfortunately require count(), and a "counter" variable, and incrementation.
I have a json file with a lot of records with fields for date, time and isApproved. What I am trying to do is to create a json rray that has dates for all the records that are approved. And the dates have all the hours that are booked for the current date.
So from this... :
[{"fullName":"Jojn Petkobsky","userName":"user1","phone":"12415455","email":"ees#asd.com"date":"11\/16\/2016","time":"1pm ","reason":"ReaReasonReaeason","isApproved":0,"label":"warning","status":"Approved"},{"fullName":"Zoltan Heinkelman","userName":"user2","phone":"12415455","email":"ees#asdd.com"date":"11\/16\/2016","time":"2pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"}{"fullName":"Jojn Petkobsky","userName":"user1","phone":"12415455","email":"ees#asd.com"date":"11\/16\/2016","time":"1pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"},{"fullName":"Frank Heinkelman","userName":"user3","phone":"12415455","email":"ees#asddd.com"date":"10\/11\/2016","time":"2pm ","reason":"ReaReasonReaeason","isApproved":1,"label":"warning","status":"Approved"}]
...i can have something like this, so i can have all the booked hours for a given date.
{"12/11/16"😞
{"time" :"10am"},
{"time" :"1pm"},
{"time" :"5pm"}
]
"12/10/16"😞
{"time" :"9am"}
]
}
I tried with something like this, but couldn't really finish it :
$string = file_get_contents("appointments.json");
$json_a = json_decode($string, true);
$date;
$datesTimes = array();
foreach($json_a as $json_r){
if ($json_r['isApproved']==1) {
$date = $json_r['date'];
//another foreach?
}
}
Any help will be appreciated!
As I mentioned in the comments, your JSON is NOT valid so I have fixed it to a point to show how it can be done.
//Fixed JSON as much as I could to show in example.
$json = '
[
{
"fullName": "Jojn Petkobsky",
"userName": "user1",
"phone": "12415455",
"email": "ees#asd.com",
"date": "11\/16\/2016",
"time": "1 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
},
{
"fullName": "Kitson88",
"userName": "user2",
"phone": "122323325",
"email": "eadasds#asasdasdd.com",
"date": "11\/16\/2016",
"time": "12 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
},
{
"fullName": "Jamie",
"userName": "user2",
"phone": "122323325",
"email": "eadasds#asasdasdd.com",
"date": "12\/16\/2016",
"time": "8 pm",
"reason": "ReaReasonReaeason",
"isApproved": "0",
"label": "warning",
"status": "Approved"
}
]
';
$array = json_decode($json, true);
//This will be you rnew Array for holding the needed data.
$approved = [];
foreach ($array as $value) {
if ($value['status'] === 'Approved') { //Any check really which will validate Approved
if (array_key_exists($value['date'], $approved)) { //Check if key exists note** will only work on 1D Array
array_push($approved[$value['date']], $value['time']); //If so, then append
} else { //If not, then create it and add value
$approved += [$value['date'] => [$value['time']]];
}
}
}
//Encode back to JSON
$newJson = json_encode($approved);
Output as JSON
{
"11\/16\/2016": ["1 pm", "12 pm"],
"12\/16\/2016": ["8 pm"]
}
http://php.net/manual/en/function.array-key-exists.php
http://php.net/manual/en/function.array-push.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