JSON to HTML table with PHP - php

How can I display the JSON below in a HTML table with PHP/HTML? I saw some other examples so far but I cant find out how I could use them with my JSON because there is the JSONArray and record section infront of the data.
{"JSONArray":{"record":[{"joined":1396627177212,"name":"kate","rank":"MEMBER","id":"424a0dc79bbb49971a599c80b9d8","dailyCoins-11-9-2015":200},{"joined":1396629936746,"name":"verna","rank":"MEMBER","id":"042896991242f9889d3276f83861","dailyCoins-11-9-2015":590},{"joined":1397048326142,"name":"lucy","rank":"MEMBER","id":"f36ca59409a60a81b110cf6ac714"},{"joined":1411762368798,"name":"christopher","rank":"MEMBER","id":"25108a666d451a923abb19213197","dailyCoins-10-9-2015":880,"dailyCoins-11-9-2015":475},{"id":"b5b733529e4a92ba8f7e2b481290","rank":"MEMBER","joined":1440161306320},{"id":"d2ff8bb9817440aae5c140b81955","rank":"MEMBER","joined":1440611487342},{"id":"e7ede489e4078798fd2c69ee8be6","rank":"MEMBER","joined":1442934056516,"dailyCoins-11-9-2015":460},{"id":"dd9ecd7a5c0f40c265dc6487261c","rank":"MEMBER","joined":1443546076415,"dailyCoins-10-9-2015":520,"dailyCoins-11-9-2015":200},{"id":"aafe27c0544fa394da721aebb220","rank":"MEMBER","joined":1443546124859},{"id":"270bea34095147863c11c7a62ea3","rank":"MEMBER","joined":1443546454759,"dailyCoins-10-9-2015":100},{"id":"a97f1d0ed0a44a928231c6fd9c7c","rank":"MEMBER","joined":1443546461462,"dailyCoins-10-9-2015":400,"dailyCoins-11-9-2015":220},{"id":"4ec268a2d18445a9399a3706b416","rank":"MEMBER","joined":1443546587154,"dailyCoins-11-9-2015":400},{"id":"26114b8edd184483895447d016f5","rank":"MEMBER","joined":1443546851165,"dailyCoins-10-9-2015":50,"dailyCoins-11-9-2015":980},{"id":"cca06c6cfa4cb7b3feb491b2a33c","rank":"MEMBER","joined":1443547050965},{"id":"cba38c69d199448d29bc315f850c","rank":"MEMBER","joined":1443547055696},{"id":"aad9060b693e4dc431687f91f404","rank":"MEMBER","joined":1443547070245,"dailyCoins-10-9-2015":80},{"id":"38876b0a546d44b8bf4f1d224a64","rank":"MEMBER","joined":1443547325591,"dailyCoins-11-9-2015":100},{"id":"6a35e9dfc0e842af93e8200e4d5a","rank":"MEMBER","joined":1443548006094},{"id":"13e287923dcb489c398512066348","rank":"MEMBER","joined":1443548827377},{"id":"a63d75a7db4674h6f2d81efedb1e6","rank":"MEMBER","joined":1443548952273,"dailyCoins-10-9-2015":255},{"id":"1e036c43824736b7a43636652f53","rank":"MEMBER","joined":1443549877348,"dailyCoins-10-9-2015":720,"dailyCoins-11-9-2015":380},{"id":"23a331cfacd844903084c075a04e","rank":"MEMBER","joined":1443549911657,"dailyCoins-10-9-2015":480},{"id":"229638c216a34acd97730b661615","rank":"MEMBER","joined":1443550075437},{"id":"5fa71907e8814cbdcdf730c116b5","rank":"MEMBER","joined":1443550083753,"dailyCoins-10-9-2015":60},{"id":"cbaf32d0c3ab4e9d690655df2ab2","rank":"MEMBER","joined":1443552053749,"dailyCoins-10-9-2015":290},{"id":"684d053c532b4095f100695e86e1","rank":"MEMBER","joined":1443552064766,"dailyCoins-10-9-2015":100,"dailyCoins-11-9-2015":30},{"id":"c9b75606f7e84e91998bc8a905d1","rank":"MEMBER","joined":1443553369085},{"id":"301bfd2965424562d8bc4e633dd3","rank":"MEMBER","joined":1443553480028,"dailyCoins-10-9-2015":130},{"id":"0cf8af3ff14c0984a56fe03562ba","rank":"MEMBER","joined":1443553490690},{"id":"d3e29112b0863cb0c5087d136667","rank":"MEMBER","joined":1443553994063},{"id":"6c1d648ea482429babd18cd151f4","rank":"MEMBER","joined":1443628880615,"dailyCoins-10-9-2015":190,"dailyCoins-11-9-2015":25},{"id":"a5c38d3f77af4678ej40cc069a8ec","rank":"MEMBER","joined":1443811816283,"dailyCoins-10-9-2015":230,"dailyCoins-11-9-2015":25},{"id":"16ab1b04504a33bd504fc72d580c","rank":"MEMBER","joined":1443816233615,"dailyCoins-10-9-2015":125,"dailyCoins-11-9-2015":395},{"id":"1f08be5b8a4ea92d91f24f209ed4","rank":"MEMBER","joined":1444211861989,"dailyCoins-10-9-2015":560,"dailyCoins-11-9-2015":120},{"id":"27adaa178844cbfc02770a443cbf","rank":"MEMBER","joined":1444389831435,"dailyCoins-10-9-2015":200},{"id":"53422792b14b600f46b3a4455930","rank":"MEMBER","joined":1444396739744,"dailyCoins-10-9-2015":670,"dailyCoins-11-9-2015":530},{"id":"3caa1a6c889a4d6e93cba50577a8","rank":"MEMBER","joined":1444397559705,"dailyCoins-10-9-2015":720,"dailyCoins-11-9-2015":820},{"id":"a4de5bb8904b5f474ba64e9760f1","rank":"MEMBER","joined":1444397625609,"dailyCoins-11-9-2015":570},{"id":"be99524ef644ec57d9d46419073f","rank":"MEMBER","joined":1444397712148,"dailyCoins-10-9-2015":780,"dailyCoins-11-9-2015":980},{"id":"9f9a8a5d934024b3e87f7a806bc8","rank":"MEMBER","joined":1444397735181,"dailyCoins-11-9-2015":230},{"id":"86f02fc1ccdee8b8e4e8a960be7d","rank":"MEMBER","joined":1444398374370},{"id":"a738f19606a44a54974b9bbabc4b","rank":"MEMBER","joined":1444398790078,"dailyCoins-10-9-2015":355,"dailyCoins-11-9-2015":160}],"extra":[],"timestamp":1444598000},"api":{}}

Here is the code you want:
$json = '{"users":[{ "user": "Carlos", "age": 30, "country": "Spain" }, { "user": "John", "age": 25, "country": "United States" }, { "user": "Mike", "age": 28, "country": "Canada" }]}';
$arr = json_decode($json, true);
echo "<table><tr><th>user</th><th>age</th><th>country</th></tr>";
foreach($arr['users'] as $item){
echo "<tr><td>".$item['user']."</td><td>".$item['age']."</td><td>".$item['country']."</td></tr>";
}
echo "</table>";
Just convert the json to array and then use a foreach and access each item property.

Related

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

PHP convert JSON array to nested

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

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.

Get Json Object from external URL with PHP

I have an URL that returns the JSON object below:
{
"addressList": {
"addresses": [
{
"id": 0000000,
"receiverName": "Name Example",
"country": {
"id": "BRA",
"name": "Brasil"
},
"state": {
"id": "SP"
},
"city": "São Paulo",
"zipcode": "00000000",
"type": "Residential",
"street": "000, St Example",
"number": 00,
"neighborhood": "Example",
"hash": "1bf09357",
"defaultAddress": false,
"notReceiver": false
}
]
}
}
I want to get the state value, how can I retrieve that with PHP?
I tried, something like this, but I couldn't get the state value, that should be SP in this case.
$string = '{ "addressList": { "addresses": [ { "id": xxxxxx, "receiverName": "XXXXX XXXXX", "country": { "id": "BRA", "name": "Brasil" }, "state": { "id": "SP" }, "city": "São Paulo", "zipcode": "03164xxx", "type": "Residential", "street": "Rua xxx", "number": xx, "neighborhood": "xxxxx", "hash": "xxxxx", "defaultAddress": false, "notReceiver": false } ] } }';
$json_o = json_decode($string);
$estado = $json_o->state;
How can I achieve the result I want?
Your JSON is not valid - you can validate it on jsonlint.com (it's invalid due to incorrectly formatted numeric values - "id" : 000000).
From then on, you can decode the value and access your data:
$json_o = json_decode($string);
$estado = $json_o->addressList->addresses[0]->state->id;
If you don't have access to the code that generates the JSON, you can attempt to run a regex to match, replace & wrap the numerical values with ":
$valid_json = preg_replace("/\b(\d+)\b/", '"${1}"', $str);
Note: The above is just an example - you'll have to figure out a case where a numerical value is already wrapped by ".
Your JSON has a couple of syntax errors:
"id": 0000000
"number": 00
JSON doesn't support leading zeros. If precise formatting is important, use strings:
"number": "00"
"id": "0000000"
Alternatively, use well-formed integers in the JSON (saves space) and convert them to formatted strings in PHP.
Once you've fixed your JSON, you can access the state->id value of the first address as I do below. When you decode JSON from an untrusted source, be prepared to do some error handling:
$json_string ="..."; //your source, to be decoded
$json_o= json_decode($json_string);
if(is_null($json_o)): //there was an error decoding
$errno = json_last_error();
$err_msg = json_last_error_msg();
die("Json decode failed: Error #$errno: $err_msg");
endif;
//we get here if json_decode succeeded. To get "SP", do...
$stateID = $json_o->addressList->addresses[0]->state->id;
Try:
$json_o = json_decode($string, true);
$estado = $json_o['addressList']['addresses'][0]['state']['id'];

Counting results displayed

I would like to know how to count how many people follows someone in Instagram and place the number in a var, Instagram gives you this link:
https://api.instagram.com/v1/users/3/followed-by?access_token=xxxxxxxxx.xxxxxxxxxxxxxxxxxxxx
And displays a result like so
{
"data": [{
"username": "meeker",
"first_name": "Tom",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_6623_75sq.jpg",
"id": "6623",
"last_name": "Meeker"
},
{
"username": "Mark",
"first_name": "Mark",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_29648_75sq_1294520029.jpg",
"id": "29648",
"last_name": "Shin"
},
{
"username": "nancy",
"first_name": "Nancy",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_13096_75sq_1286441317.jpg",
"id": "13096",
"last_name": "Smith"
}]
}
How can I count how many are there and place it in a var, lets say:
<? echo "You are been follow by ".$followers." users!"; ?>
To display: You are been follow by 3 users!
You would need to use json_decode to to decode the JSON response, then access the resulting object's data attribute (an array of 'follower' objects), and count that:
$json = '{
"data": [{
"username": "meeker",
"first_name": "Tom",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_6623_75sq.jpg",
"id": "6623",
"last_name": "Meeker"
},
{
"username": "Mark",
"first_name": "Mark",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_29648_75sq_1294520029.jpg",
"id": "29648",
"last_name": "Shin"
},
{
"username": "nancy",
"first_name": "Nancy",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_13096_75sq_1286441317.jpg",
"id": "13096",
"last_name": "Smith"
}]
}';
$json = json_decode($json);
echo "You have " .count($json->data) ." followers"
OR
$json = json_decode($json,true);
echo "You have " .count($json['data']) ." followers"
You are getting as a json string, you need to decode it using json_decode.
$data = json_decode($string,true);
$followers = count($data['data']);
CodePad Demo.
You need to use json_decode() which will return you a PHP array. Then all you need to do is to count() all the values in the array with 'data' key.
You can use json_decode
$array = json_decode($str);
Then give
echo count($array);
It will give total count of users
simple way to count entries returned asJSON
echo count(json_decode($followers);
Use json_decode() to create a PHP array from the JSON. Then you can simply do a count() on that:
$jsonData = json_decode($yourAPIResult);
echo count($jsonData->data);
Be aware, however, that you probably should set up some error handling in case the API did not return a proper JSON string. So something like this might be better:
if (is_null($jsonData) || !property_exists($jsonData, 'data')) {
echo '?';
} else {
echo count($jsonData->data);
}

Categories