I have multiple JSON files with different structures. What I want to do is to automatically display these JSON outputs with HTML.
Some of my JSON outputs are as follows: (Think of each of these as separate files and need to be processed separately)
{
"parts": [
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
... other objects
]
}
{
"licenses":[
{
"driver":"John",
"year":26,
"info":null
},
... other objects
]
}
Now, to process these files, I send the page name with GET on PHP and I want the corresponding JSON output to be printed to the screen with HTML as <span>$key</span> -> <span>$value</span>
How can I make this dynamic JSON output read event with PHP? Do I need to create a recursive function?
Because the files have different structures from each other. I hope I was able to explain my problem. Thanks already for yours help.
I suggest the following:
get required JSON file name from GET or POST, for example:
$jsonfilename = $_GET['file'];
The above does not include any security protection! this is a separate topic,
so do some research.
load your json file and parse it:
$json = file_get_contents('/path/'.$jsonfilename);
$data = json_decode($json, true);
read your json data:
foreach ($data as $key=>$value){
echo ''.$key.' -> '.$value.'';
}
A simple example for your PARTS file:
$json = '
{
"parts":
[
{
"#attributes": {
"id": "part1"
},
"car": "Peugeot",
"service": 5,
"location": 2996,
"price": "44.95",
"date": "2000-10-01"
},
{
"#attributes": {
"id": "part2"
},
"car": "Renault",
"service": 8,
"location": 3100,
"price": "99.95",
"date": "2022-03-01"
}
]
}';
$arr = json_decode($json, true);
foreach($arr["parts"] as $part) {
foreach($part as $k => $v){
if($k == "#attributes")
echo "<h1>" . $v["id"] ."</h1>";
else
echo "<span>$k</span> -> <span>$v</span> <br/>";
}
}
This produces:
Related
i wanna convert a json file has text like this design json_text https://phponlines.com/result/e2j9RgRnm7
$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);
var_dump(json_encode($json_decoded));
then after i edit it to get same design again but i get different deisng instead in one line
[{"id":"1","name":"john","bd":[]},{"id":"2","name":"gary","bd":[1,2]}]
but what i want is
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]
As stated in my comments above, this is not particularly advisable, and writing any portion of a JSON file by hand is even more inadvisable.
But if you do not wish to see the light, then at least the use the minimal amount of darkness.
// polyfill for PHP<8.1
if (!function_exists('array_is_list')) {
function array_is_list(array $a) {
return $a === [] || (array_keys($a) === range(0, count($a) - 1));
}
}
function do_weird_json(array $input) {
if( ! array_is_list($input) ) {
throw new Exception('Input data must be a list');
}
return sprintf("[\n%s\n]\n", implode(",\n", array_map('json_encode', $input)));
}
$json_text = '
[
{"id": "1", "name": "john", "bd": []},
{"id": "2", "name": "gary", "bd": [1, 2]}
]';
$json_decoded = json_decode($json_text, true);
$json_decoded[1]['name'] = 'bill';
var_dump(do_weird_json($json_decoded));
Output:
string(74) "[
{"id":"1","name":"john","bd":[]},
{"id":"2","name":"bill","bd":[1,2]}
]
"
Again, the best thing to do would be to leave the JSON as the default, not-human-friendly format and use a client-side tool like jq, etc to reformat the JSON for you for viewing purposes.
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 using this code $json_output = (json_decode($json, true)); to transform from JSON to an associative array in PHP.
The resulting array looks too compĺex to me, I need to print only some keys and values but they are nested and so far I haven't been able to do it, the examples I had follow for printing are too basic for this.
This is part of my JSON:
{
"project": {
"company": "Company Name SA de CV",
"name": "Project Name",
"files": [
{
"project-id": "666666",
"filenameOnDisk": "HH-ORG-CMD-GUI-File.docx",
"uploaded-date": "2018-01-29T21:20:56Z",
"private": "0",
"version-id": "3939061",
"status": "active",
"tags": [
{
"name": "OPD",
"id": "25047",
"color": "#9e6957"
}
],
"id": "3796128",
"last-changed-on": "2018-01-29T21:21:46Z",
"versions": [],
"uploaded-by-user-first-name": "Someone",
"uploaded-by-user-last-name": "Anything",
"name": "HH-ORG-CMD-GUI-GUIA_RAPIDA_PARA_CREAR_PROCESOS",
"size": "262747",
"category-name": "Instructivos"
},
{
"project-id": "666",
etc...,
},
When parsed looks like
How do I print (lets say) filenameOnDisk and id keys of the Files array.
I don't know how to get to that nested array.
echo $json_output['project']['files'][0]['project-id'];
echo $json_output['project']['files'][0]['filenameOnDisk'];
echo $json_output['project']['files'][0]['version-id'];
Or you could put it in a foreach loop using an array of values you want (as long as they're all in the 'files' array). Eg.
$wantedValues = array("project-id","filenameOnDisk","version-id");
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][0][$value];
}
I Just needed to add a couple of lines at the code provided by #SeeSamRun in order to get the full "Files" array.
$filesArray = $json_output['project']['files'];
$filesSize = count($filesArray);
$wantedValues = array("project-id","filenameOnDisk","version-id");
for ($i=0; $i < $filesSize; $i++) {
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][$i][$value];
}
}
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/
I am trying to query and parse Yahoo fantasy sports data and show results in a friendly format.
Here is the JSON I get back from Yahoo from a successful request...
{
"fantasy_content": {
"xml:lang": "en-US",
"yahoo:uri": "\/fantasy\/v2\/users;use_login=1\/teams",
"users": {
"0": {
"user": [
{
"guid": "1234567890"
},
{
"teams": {
"0": {
"team": {
"team_key": "268.l.auto.t.209996",
"team_id": "209996",
"name": "Team Test",
"type": "auto"
}
},
"1": {
"team": {
"team_key": "273.l.auto.t.27741",
"team_id": "27741",
"name": "Team API",
"type": "auto"
}
},
"count": 2
}
}
]
},
"count": 1
},
"time": "29.808044433594ms",
"copyright": "Data provided by Yahoo! and STATS, LLC",
"refresh_rate": false
}
}
I am looking to get the team names from the teams array. I have tried using the following PHP code (among countless variations of it) to drill to the node I need but I am not having any luck.
$obj=json_decode($json);
$data = $obj->fantasy_content->users->user->teams->team;
foreach($data as $d){
echo 'name: ' . $d->name ; //prints php
}
I am hoping that someone might be able to provide a working example using the JSON above as I have clearly failed at this. Any help would be greatly appreciated.
Thanks in advance!
Try this
$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams;
foreach($data as $d){
echo 'name: ' . $d->team->name ; //prints php
}
EDIT
you can use the cout to loop through the names
$obj=json_decode($json);
$data = $obj->fantasy_content->users->{'0'}->user[1]->teams;
for($i = 0; $i < $data->count; $i++){
echo 'name: ' . $data->{$i}->team->name ; //prints php
}