How to retrive the following json data in php - php

i've the following json data with the following structure
{
"page": 0,
"items": 43,
"total": 43,
"incentiveItems": {
"incentiveItem": [
{
"#id": "1111",
"name": "...",
"program": {
"#id": "6765",
"$": "NAME"
},
"admedia": {
"admediumItem": {
...
and more, to parse the data in php i do a simple foreach...
$obj = json_decode($jsonData);
echo $obj->items;
echo '<table><tr><td>Nome</td><td>Descrizione</td><td>Codice</td></tr>';
foreach($obj->incentiveItems->incentiveItem as $programma ) {
so, the problem is that i can't call the "$" :" NAME" value, coz if i use (for ex)
$programma->program->$
$programma->program['$']
$obj->incentiveItems->incentiveItem->program->$ or ['$']
it crash
and the same is for the #id field.
can someone help me? Thanks

Tyr decoding json as associative array:
$obj = json_decode($jsonData, true);
echo $obj['items'];
echo '<table><tr><td>Nome</td><td>Descrizione</td><td>Codice</td></tr>';
foreach($obj['incentiveItems']['incentiveItem'] as $programma ) {
echo $programma['#id'];

I believe you can use single quotes and curly brackets to access it
$obj->incentiveItems->incentiveItem->program->{'$'}
$obj->incentiveItems->incentiveItem->program->{'#id'}

Related

Generate dynamic html with JSON output (with php)

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:

Not getting the array on JSON

Hello I am trying to break down JSON data
** {
"message": "gradeExam.php",
"id": "171",
"student_id": "dfd",
"questions": [{
"question_id": "0",
"student_input": "def doubly_"
},
{
"question_id": "1",
"student_input": "asd"
}
]
}**
using PHP
$json = file_get_contents('php://input');
$_POST = json_decode($json, true);
$input = $_POST["questions"];
foreach($input as $questions)
{
$quest_id[] = $questions["question_id"];
$student_input[] = $questions["student_input"];
}
echo $quest_id;
echo $student_input;
BUT keep getting a response of.. ArrayArrayArray[]
I am trying loop and get the data of question_id: 0, student_input: def doubly_, question_id: 1, student_input: asd.
What am I doing wrong?
Everything that you have done is correct except these 2 lines.
echo $quest_id;
echo $student_input;
As $quest_id and $student_input are arrays we cannot use the echo function. Instead, you can use the print_r function as below
print_r($quest_id);
print_r($student_input);

How to decode this json with foreach

This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>

Decoding a JSON object and echo a specific value?

I have a PHP page where I reference a JSON object that looks like this:
{
"body": {
"zip": "02110",
"stores": [
{
"storeEmail": "email#email.com",
"storeName": "Name",
"city": "City",
"Availability": {
"123": {
"Quote": "daily",
"Display": "available",
}
},
},
Each JSON object contains multiple "stores", above is one example.
I can currently echo the store name by using this:
echo "<br>".$phpArray->body->stores{0}->storeName;
How do I echo the value "123" from the sample JSON? I would also like to echo the quote as a separate variable. The value "123" will change for different searches. Any help would be greatly appreciated!
$phpArray = json_decode($json, true);
foreach($phpArray['body']['stores'] as $store) {
echo $store['storeName'];
foreach{$store['Availabilty'] as $avail => $info) {
echo $avail; // 123
echo $info['Quote'];
}
}
$b = json_decode($a);
var_dump(key($b->body->stores{0}->Availability));
var_dump(reset($b->body->stores{0}->Availability)->Quote);
or a loop for stores
foreach($b->body->stores as $store) {
var_dump(key($store->Availability));
var_dump(reset($store->Availability)->Quote);
}

Insert JSON values in MYSQL using PHP

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/

Categories