I am revising my php knowledge. I have external.js file in which there are records in it.
var data = [{
"id": "71002",
"fullName": "Chenz",
"title": "Mechanical Engineer",
"reportTo": "Structural Manager",
"Reportingday": "2017-01-01T09:00:00.000Z" }, .....so on
I need to create html/php page from this record and list all the data above. How will I achieve this thing?
Thank you.
Your Data:
var data = [{"id": "71002","fullName": "Chenz","title": "Mechanical Engineer","reportTo": "Structural Manager","Reportingday": "2017-01-01T09:00:00.000Z" },
Looks to be JSON. You should look at the json_decode() and json_encode() functions. It will convert JSON to an array and an array to JSON. Once in an array you can easily used that to create web pages.
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-encode.php
<?php $myData = json_decode('data = [{"id": "71002","fullName": "Chenz","title": "Mechanical Engineer","reportTo": "Structural Manager","Reportingday": "2017-01-01T09:00:00.000Z" }');
Would allow you to call the values something like so
echo '<span>'.$myData->data['id'].'</span>';
Would return
<span>71002</span>
You can test and look at the data once in array format with something like
die(print_r($myData));
Related
In my database I have POSTed following JSON with REST API:
{
"author": "Someone",
"hero_name": "Iron Man",
"hero_desc": ["Iron", "Man"],
}
Now in database Table, the entry says only Array for the hero_desc.
I cannot figure out how to get the actual items in that array.. for example to fetch Iron from hero_desc.
Here is how it gets returned with GET request:
{
"id": "11",
"user_id": "1",
"author": "Someone",
"hero_name": "Iron Man",
"hero_desc": "Array",
}
I am quite new to PHP so I am worried that I would need to mess up my whole app architecture to get this to work. I though PHP can handle fetching arrays by default if it sees it's an JSON Array.
use json_decode(); function for change json to array
$json_to_array = json_decode($your_json_variable_name);
You could change array data to JSON with json_encode In one hand you have an array without the key that code makes a number key for that in another hand if have an array with the key you can get that inside JSON with that key.
$content ='your content or your array data';
header('Content-Type: application/json; charset=utf8');
echo json_encode($content);
when i use....
var jsonData = JSON.parse(xhttp.responseText);
i get an error => "JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 50 of the JSON data"
this is my JSON data from a php script
{"results":[{"oldID":5,"oldMain":"News papers"}]}{"results":[{"oldID":3,"oldMain":"Construction"}]}{"results":[{"oldID":2,"oldMain":"Banking Files"}]}{"results":[{"oldID":1,"oldMain":"Technologies"}]}
Can some please help?.... Thanks
A little bit late to the party, but #igniz87 and #Benjamin James Kippax's answers open your website to security issues, and it is so dangerous to follow their example.
As Owasp reads,
ALWAYS RETURN JSON WITH AN OBJECT ON THE OUTSIDE
Hence, so as to be a layer protected from the barbarism of hackers, you need to ALWAYS have the outside primitive be an object for JSON strings. As you can clearly see, the mentioned people's answers do not follow this crucial security rule.
Owasp, moreover, brings an example and says that a JSON like the following is EXPLOITABLE:
[{"object": "inside an array"}]
Yet, the following JSONs are not,
{"object": "not inside an array"}
{"result": [{"object": "inside an array"}]}
You need to remove the duplicate key element and change it in the following way so you will have an object on the outside.
{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}],
"resultss": [{
"oldID": 3,
"oldMain": "Construction"
}]}
Here, actually you should have brought you php code, as the problem is with that php code which is sending the JSON. When you want to send the JSON try to make an array of your data. I do the following way.
$data = [];
foreach ($results as $res) {
$t = [];
$t['oldID'] = $res['oldID'];
$t['oldMain'] = $res['oldMain'];
$data[] = $t;
}
echo json_encode(['results' => $data]);
You'd better send your php code which is lacking here. My php script does not contain all of your code, but it gives you idea how to do it.
I have had the same problem for the past several years.
Sometimes the problem is not related to invalid JSON .. like me now.. the problem is that I must use stringify before JSON.parse
var db = JSON.stringify(data);
var db = JSON.parse(db);
And sometimes in php you must use json_encode($data) correctly.
And sometimes your JSON is not valid ( Online JSON Validator )
The JSON is not valid. If it is possible, you can update the JSON as following
{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}],
"resultss": [{
"oldID": 3,
"oldMain": "Construction"
}]}
And also JSON should not contain duplicate key elements. Also you can club the JSON to JSONArray like this
[{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}]
},
{
"results": [{
"oldID": 3,
"oldMain": "Construction"
}]
}]
it's not a valid json, you must wrap it in array. the valid json is like this
[{
"results": [{
"oldID": 5,
"oldMain": "News papers"
}]
}, {
"results": [{
"oldID": 3,
"oldMain": "Construction"
}]
}, {
"results": [{
"oldID": 2,
"oldMain": "Banking Files"
}]
}, {
"results": [{
"oldID": 1,
"oldMain": "Technologies"
}]
}]
take a look at the bracket [ ] at the start and the end of string , and the , to split the object.
this some online json linter here to check if your json is valid.
Your code is invalid.
Your code;
{"results":[{"oldID":5,"oldMain":"News papers"}]}{"results":[{"oldID":3,"oldMain":"Construction"}]}{"results":[{"oldID":2,"oldMain":"Banking Files"}]}{"results":[{"oldID":1,"oldMain":"Technologies"}]}
Your code validated;
[{"results":[{"oldID":5,"oldMain":"News papers"}]},
{"results":[{"oldID":3,"oldMain":"Construction"}]},
{"results":[{"oldID":2,"oldMain":"Banking Files"}]},
{"results":[{"oldID":1,"oldMain":"Technologies"}]}]
The problem is that you had multiple JSON root elements. These also weren't comma separated. They also need wrapping in [], which will turn it into an object. If you don't want to wrap your response in [], you can return the string without the [] and instead do this;
JSON.parse('['+yourreponse+']') which will parse the JSON correctly.
Above answer are correct i.e. your json syntax is incorrect. Correcting your syntax would solved the problem (as suggested)
My case was a little different. I was returning json in response to ajax calls. Those jsons where returned by php using a if else construct. Where I mistakenly omitted one else;
if (!empty($_GET['arg1']))
echo getTrainings($filter, 'arg1');
elseif (!empty($_GET['arg2']))
echo getTrainings($filter, 'arg2');
if (empty($_GET['arg3']))
echo getTrainings($filter, 'arg3');
elseif (empty($_GET['arg4']))
echo getTrainings($filter, 'arg4');
So in fact two json where being returned instead of one, that caused problem for $.parseJSON(result);
var par = $.parseJSON(result);
I'm trying to get specific data from a JSON file (url) and save that data in a PHP variable.
The JSON comes from an url. For example:
https://euw.api.pvp.net/api/lol/euw/v1.4/summoner/by-name/Viducius?api_key=secret
The JSON file:
{
"viducius": {
"id": 26541044,
"name": "Viducius",
"profileIconId": 591,
"revisionDate": 1480517139000,
"summonerLevel": 30
}
}
So my question is how can I get the data from id, in this case 26541044, and put that into a PHP variable?
Also to get the data from the JSON file, I have to search for the id while the array name 'viducius' came from a PHP variable.
TLDR:
The array $arrayName contains an id '26541044' that has to be saved into variable $id
Is there someone who can help me with this? I was thinking on doing this in jQuery but if it's easier with PHP only thats fine too.
That is a JSON String, therefore you need to convert it into a PHP data structure. PHP Provides json_decode() to do that.
$json_string = '{"viducius": {
"id": 26541044,
"name": "Viducius",
"profileIconId": 591,
"revisionDate": 1480517139000,
"summonerLevel": 30
}
}';
$obj = json_decode($json_string);
$id = $obj->viducius->id;
echo 'id = ' . $id;
{
"Group": [
{
"name": "HolderOne",
"operators": [
{
"username": "ken",
"status": 3
},
.....etc.....
The JSON feed I am attempting to manipulate has to format above.
I wish to be able to display username and status.
$json = file_get_contents("urlhere");
$obj=json_decode($json);
echo $obj->username;
echo $obj->status;
This obviously doesn't work as they are nested(?) within the feed...I have tried:
$obj->Group[0]->name->operators->username
and
$obj->Group[0]->name->username
to no avail (as well as json_decode with ,true and ['name'], etc).
Am I being particularly dim?
when I do a var dump, the data is being collected from the feed okay.
The best way to figure this out is to iteratively do print_r's:
print_r($obj)
//prints what you see above
print_r($obj['Group']
//prints the Group Object
print_r($obj['Group'][0])
//prints first element in Group Object
print_r($obj['Group'][0]['operators'])
//etc.....
That's how I find out how to access these deep elements if I get a little stuck. Though it appears to me that you want:
$obj->Group[0]->operators[0]->username
I'm trying to get into just data from
{
"data": [{
"media_count": 3045,
"name": "snow",
},
{
"media_count": 79,
"name": "snowman",
},
{
"media_count": 40,
"name": "snowday",
},
{
"media_count": 29,
"name": "snowy",
}]
}
I've been trying, using:
$obj = json_decode($res[0], true);
echo $obj['data']; //this returns an array
I also tried this:
$obj = json_encode($res[0], true);
echo $obj; // this returns json, but not inside `data`
"data": [{
"media_count":54373,
"name":"test"
}]
I just want to get inside data. How would I do so?
Thanks in advance!
UPDATE: Sorry to mention, I would like this in json format please
eventually, I would like to only see
{
"media_count":54373,
"name":"test"
}
Something like thiat
Use json_encode() to get what you want:
$obj = json_decode($res[0], true);
echo json_encode($obj['data']);
In your first example, $obj['data'] returns an array because that's how the JSON is set up. According to the JSON, data is a collection of elements.
To access within the array, you can do this:
foreach($obj['data'] as $object) {
print_r($object);
}
You can also index into it as you want:
print_r($obj['data'][0]);
EDIT
If I'm getting you correct, you want to convert the first JSON to this:
"data": [{
"media_count":54373,
"name":"test"
}]
If so, that is not possible since the second fragment is not valid JSON. (use http://jsonlint.com)
firstly access the data item of the json array;
$obj1=$obj[item];
$sizeobj=sizeof($obj1);
for($i=0;$i<$sizeobj;$i++)
{
// your code to access the data items
// for eg $obj[item][$i][media_count}
}