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.
Related
This is my php file code where i am fetching data from thecatapi
i needed the specific format for datatable
$xml=file_get_contents('https://thecatapi.com/api/images/get?format=xml&results_per_page=3');
$xml = new SimpleXMLElement($xml);
$datas=array();
$datas['rows'] = $xml->data->images;
echo json_encode($datas, true);
Output is:
{"total":50,
"rows":{"image":[
{"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
"id":"e0i",
"source_url":"http:\/\/thecatapi.com\/?id=e0i"
},
{"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
"id":"MTYwNDE0MQ",
"source_url":"http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
},{
"url":"https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
"id":"bon",
"source_url":"http:\/\/thecatapi.com\/?id=bon"
}
]
}
}
but i wanted in this json form
{
"total": 800,
"rows": [
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
{
"url": 0,
"id": "Item 0",
"source_url": "$0"
},
Just came up with an alternativ solution. Change this line:
$datas['rows'] = $xml->data->images;
to this:
$datas['rows'] = $xml->data->images->image;
otherwise you can still do this
Decode the json string into an object and modify it suit your needs.
$stdClassObject = json_decode($jsonData);
$stdClassObject->rows = $stdClassObject->rows->image;
$newJsonData = json_encode($stdClassObject, JSON_PRETTY_PRINT);
echo '<pre>';
print_r($newJsonData);
echo '</pre>';
New output:
{
"total": 50,
"rows": [
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=e0i",
"id": "e0i",
"source_url": "http:\/\/thecatapi.com\/?id=e0i"
},
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=MTYwNDE0MQ",
"id": "MTYwNDE0MQ",
"source_url": "http:\/\/thecatapi.com\/?id=MTYwNDE0MQ"
},
{
"url": "https:\/\/thecatapi.com\/api\/images\/get.php?id=bon",
"id": "bon",
"source_url": "http:\/\/thecatapi.com\/?id=bon"
}
]
}
I'm trying to get JSON by name and save it as a variable with everything related to that nest,
what would the best way to accomplish this?
(in my scenario the names are unique)
[{
"name": "Joe",
"age": "30",
"gender": "male"
},
{
"name": "Logan",
"age": "27",
"gender": "male"
}]
to something like this
{
"Joe": [{
"name": "Joe",
"age": "30",
"gender": "male"
}],
"Logan": [{
"name": "Logan",
"age": "27",
"gender": "male"
}]
}
i need to be able to search on the name to get the correct one, the API switches order so can't get it from just id
Hi This might helps you
$list = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}]';
$newjson = json_decode($list, true);
$final = [];
foreach ($newjson as $key => $value) {
$final[$value['name']][]=$value;
}
$finaloutput = json_encode($final, true);
echo "<pre>";
print_r($finaloutput);
echo "</pre>";
exit;
The output is
{"Joe":
[{"name":"Joe","age":"30","gender":"male"}],
"Logan":
[{"name":"Logan","age":"27","gender":"male"}]}
The Laravel Collections Library is a very useful lib to use cases like yours.
For this problem you could use the keyBy method!
$json = '[
{
"name":"Joe",
"age":"30",
"gender":"male"
},
{
"name":"Logan",
"age":"27",
"gender":"male"
}
]';
$array = collect(json_decode($json, true))->keyBy('name')->all();
print_r($array); // will be the array with the keys defined by the name!
See https://laravel.com/docs/5.5/collections#method-keyby
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/
How can I read several values with the same name from a JSON from Facebook, when I use this code:
$urlamandar = 'https://graph.facebook.com/'.$user."?access_token=".$access_token;
$content = file_get_contents($urlamandar);
$obj = json_decode($content, true);
$obj = json_decode($content);
It displays this:
{
"id": "XXXXXXXX",
"name": "Ricardo Capistran",
"first_name": "Ricardo",
"last_name": "Capistran",
"gender": "male",
"locale": "es_MX",
"username": "richycapy"
}
And since because there is only one ID, one NAME, one USERNAME, etc, Its quite simple place them in vars like so:
$fbuserid = $obj->{'id'};
$fbname = $obj->{'name'};
$fbusername = $obj->{'username'};
$fbemail = $obj->{'email'};
$fbbirthday = $obj->{'birthday'};
But when it comes to larger files like this code:
$urlamandar = 'https://graph.facebook.com/'.$user.'/albums?access_token='.$access_token;
Its displays a way bigger array like so:
{
"data": [
{
"id": "10150732237818223",
"from": {
"name": "Ricardo Capistran",
"id": "XXXXXXX"
},
"name": "EnterateNorte.com Photos",
"link": "https://www.facebook.com/album.php?fbid=10150732237818223&id=743158222&aid=457026",
"privacy": "custom",
"count": 31,
"type": "app",
"created_time": "2012-03-11T02:44:42+0000",
"updated_time": "2014-01-07T03:13:24+0000",
"can_upload": false
},
{
"id": "440168313222",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Timeline Photos",
"link": "https://www.facebook.com/album.php?fbid=440168313222&id=743158222&aid=220377",
"cover_photo": "10151730849598223",
"privacy": "everyone",
"count": 175,
"type": "wall",
"created_time": "2010-06-30T22:38:45+0000",
"updated_time": "2014-01-01T02:09:11+0000",
"can_upload": false
},
{
"id": "10150797320378223",
"from": {
"name": "Ricardo Capistran",
"id": "743158222"
},
"name": "Instagram Photos",
"link": "https://www.facebook.com/album.php?fbid=10150797320378223&id=743158222&aid=466555",
"cover_photo": "10151695050098223",
"privacy": "friends",
"count": 37,
"type": "app",
"created_time": "2012-04-09T23:50:08+0000",
"updated_time": "2013-12-29T08:29:15+0000",
"can_upload": false
}
],
"paging": {
"cursors": {
"after": "NDM1NjY5NjI4MjIy",
"before": "MTAxNTA3MzIyMzc4MTgyMjM="
},
"next": "https://graph.facebook.com/*my_id*/albums?access_token=*access_token*&limit=25&after=NDM1NjY5NjI4MjIy"
}
}
And I would need the “name” and “id” off all the albums, so then I can repeat this same procedure with the containing pictures
Obviously it has way more albums, I just cut it after 3 just to explain my self…
Is there a way to place them in vars? With a php “for each” some how
Thanks!
You can do something like
$obj = json_decode($content, true);
$array_album = array();
foreach($obj['data'] as $key=>$val){
$array_album[] = array("id"=>$val["id"],"name"=>$val["name"]);
echo "ID : ".$val["id"]. " NAME : ".$val["name"] ;
echo "<br />";
}
print_r($array_album); // This will have all the id and names
If you dont want to store in array then the names and id will appear in the above loop and you can do whatever you want with those values. Or use the array $array_album and loop through if you want to use it later.
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