Print JSON Content in PHP - php

I'd like to print this json
i can print the first part with the actions
PHP:
$print= json_decode($output_data);
foreach($print->actions as $mydata)
{
echo $mydata->ID.'<br><br>';
}
JSON:
{
"actions": [
{
"ID":"Search",
"name":"Select"
}
],
"content": {
"TEST": "false",
"nickname": "brad"
}
}
but i cant print the content part to show the TEST and nickname content.
Can you please help me ?
Thanks

In the assumption you Json format is like this:
{
"actions" : [{
"ID" : "Search",
"name" : "Select"
}
],
"content" : {
"TEST" : "false",
"nickmane" : "brad"
}
}
You can do it like in next example:
$print= json_decode($output_data);
// Print all actions IDs:
foreach($print->actions as $mydata)
{
echo $mydata->ID . '<br><br>';
}
// Print TEST.
echo "TEST: " . $print->content->TEST . " Nickname: " . $print->content->nickname;
Also, if you need to dump all the JSON, try this:
$print = json_decode($output_data);
print_r($print);
Or this:
$print = json_decode($output_data);
$output = print_r($print, true);
echo $output;
You can read more about print_r() and other ways to dump variables here: http://php.net/manual/es/function.print-r.php

You can do it quite simply like this:
$print= json_decode($output_data);
echo $print->content->TEST;
echo "<br/>";
echo $print->content->nickmane;
The difference from the "actions" is that "actions" is an array whereas "content" is an object, so you don't need a loop.
Click here to run a demo of this code

Your JSON is not a valid format. I appears your JSON should be the following to do what you want:
{
"actions" : [{
"ID" : "Search",
"name" : "Select"
}
],
"content" : {
"TEST" : "false",
"nickmane" : "brad"
}
}

Related

foreach loop cant find values of json object and display on php page

I got some data in my data/clients.json file and I'm trying to reach for some of the keys and values and display them in my php file. It does not work and i can not figure out why.
My clients.json file looks like:
{
"data": {
"nikajakubec": {
"name": "nika",
"loans": {
"amount": "1000",
"reason": "for garden"
}
}
}
}
And my PHP file:
<?php
$sData = file_get_contents('data/clients.json');
$jData = json_decode($sData);
$jClient = $jData->data->$sUsername;
foreach ($jClient->loans as $jLoans) {
echo "
<div>
<div>Amount:$jLoans->loans-></div>
<div>Reason:$sUserName->reason</div>
</div>";
}
?>
Do like this:-
<?php
$json = '{
"data": {
"nikajakubec": {
"name": "nika",
"loans": {
"amount": "1000",
"reason": "for garden"
}
}
}
}';
$jData = json_decode($json);
foreach ($jData->data as $user) {
echo "
<div>
<div>Amount:". $user->loans->amount ."</div>
<div>Reason: ". $user->loans->reason ."</div>
</div>";
}
Output:- https://3v4l.org/8HPV5
The field reason it's actually nested inside the loans prop, not directly in the user.
so instead of
$sUserName->reason
just go
$jLoans->reason
And also go $jLoans->amount instead of $jLoans->loans->
Consider that when you cycle $jClient->loans you are going to work on each prop of loans, which are 'amount' and 'reason'

Fetching json array in php

I have problem with fetching json array that i send with post by android app.
PHP code :
<?php
$properties_json = json_decode($_POST['property'], true);
foreach ($properties_json->properties as $pro_element) {
echo $pro_element->property_id . '<br/>';
echo $pro_element->property_name . '<br/>';
echo $pro_element->property_value . '---------';
}
JSON array that i post :
{
"properties": [
{
"property_id": "654",
"property_name": "Gender",
"property_value": "Male"
},
{
"property_id": "655",
"property_name": "Name",
"property_value": "Amin"
},
{
"property_id": "656",
"property_name": "Mobile",
"property_value": "654-451-456"
}
]
}
Error :
Invalid argument supplied for foreach()
enter image description here
json_decode($_POST['property'], true); return an array. In your code you're using it as an object. Here is the proper way :
<?php
$properties_json = json_decode($_POST['property'], true);
foreach ($properties_json['properties'] as $pro_element) {
echo $pro_element['property_id'] . '<br/>';
echo $pro_element['property_name'] . '<br/>';
echo $pro_element['property_value'] . '---------';
}
EDIT:
You can check if $_POST['property'] exist and is not null.
<?php
if(isset($_POST['property'])){
if($_POST['property'] != null and $_POST['property'] != ""){
$properties_json = json_decode($_POST['property'], true);
foreach ($properties_json['properties'] as $pro_element) {
echo $pro_element['property_id'] . '<br/>';
echo $pro_element['property_name'] . '<br/>';
echo $pro_element['property_value'] . '---------';
}
}else{
echo "POST['property'] is empty";
}
}else{
echo "Missing POST['property']";
}
You reference $properties_json->properties as if it were an object, but you converted your JSON to an array by doing json_decode($_POST['property'], true); (see the documentation of json_decode)
You either need to change the true to false or do
foreach ($properties_json['properties'] as $pro_element) {

php read of a json file - i can not read the multi tier elements

I am trying to read a json file in php, i can retrieve the root parts of the file, however whatever i try, i can not read the innner parts(child) of the json file, any help would be great
here is the json file
{
"orderId":"112-1567223-2156269x",
"legacyOrderItemId":"0218943273x4778",
"orderItemId":"2068965x7409001",
"asin":"B01K9RxxB0GQ",
"title":"xippro decs",
"merchantId":"A3H7UYG3T9xx6JDM",
"quantity":1,
"version3.0":{
"customizationInfo":{
"surfaces":[
{
"name":"Surface 1",
"areas":[
{
"colorName":"White",
"fontFamily":"Coppergate Bold",
"Position":{
"x":13,
"y":218
},
"name":"Line 1",
"Dimensions":{
"width":382,
"height":53
},
"label":"Your Text Here",
"fill":"#FFFFFF",
"customizationType":"TextPrinting",
"text":"Ruth's"
},
{
"colorName":"White",
"fontFamily":"Coppergate Bold",
"Position":{
"x":144,
"y":258
},
"name":"Customization 2",
"Dimensions":{
"width":119,
"height":17
},
"label":"Date (EST)",
"fill":"#FFFFFF",
"customizationType":"TextPrinting",
"text":"1969"
}
]
}
]
}
},
"customizationInfo":{
"aspects":[
{
"title":"Your Text Here",
"text":{
"value":"Ruth's"
},
"font":{
"value":"Coppergate Bold"
},
"color":{
"value":"#FFFFFF"
}
},
{
"title":"Date (EST)",
"text":{
"value":"1969"
},
"font":{
"value":"Coppergate Bold"
},
"color":{
"value":"#FFFFFF"
}
}
]
},
"version":"2.0"
}
and my php code is below
<?php
$file = file_get_contents('16532135318050.json', true);
$character = json_decode($file,false,400);
//print_r ($character);
echo $character->orderId . "<Br>";
echo $character->legacyOrderItemId . "<Br>";
echo $character->orderItemId . "<Br>";
echo $character->asin . "<Br>";
echo $character->merchantId . "<Br>";
echo $character->quantity . "<Br>";
echo $character->version3.0->customizationInfo->surfaces->areas[0]->colorName; // does not work
echo $character->version3.0->customizationInfo->surfaces->areas->colorName; // does not work
?>
Two issues:
version3.0 isn't a valid identifier - you should use {"version3.0"} instead.
surfaces is an array, so you should use surfaces[0]
this might work
$character->{"version3.0"}->customizationInfo->surfaces[0]->areas[0]->colorName
The reason it doesn't work is because $character->version3.0->customizationInfo->surfaces is an array and needs to be dereferenced accordingly:
$character->{'version3.0'}->customizationInfo->surfaces[0]->areas[0]->colorName

Parsing JSON with json_decode in PHP

This is the JSON data I get from our ticket-system. I would like to parse it with PHP and save the data in a database to create statistics and a dashboard so everyone can see how many tickets are open and the latest closed tickets.
I can read some of the data but not everything.
{
"address":"belgium",
"workers":{
"peter":{
"worker":"peter",
"open_close_time":"45.6 T/h",
"closed_tickets":841,
"open_tickets":7,
"last_checkin":1498768133,
"days_too_late":0
},
"mark":{
"worker":"mark",
"open_close_time":"45.9 T/h",
"closed_tickets":764,
"open_tickets":2,
"last_checkin":1498768189,
"days_too_late":0
},
"walter":{
"worker":"walter",
"open_close_time":"20.0 T/h",
"closed_tickets":595,
"open_tickets":4,
"last_checkin":1498767862,
"days_too_late":0
}
},
"total_tickets":2213,
"tickets":[
{
"id":2906444760,
"client":"297",
"processed":0
},
{
"id":2260,
"client":"121",
"processed":0
},
{
"id":2424,
"client":"45",
"processed":0
}
],
"last_closed_tickets":[
{
"id":2259,
"client":"341",
"closed_on":"2017-06-25T10:11:00.000Z"
},
{
"id":2258,
"client":"48",
"closed_on":"2017-06-20T18:37:03.000Z"
}
],
"settings":{
"address":"belgium",
"email":"",
"daily_stats":0
},
"open_close_time":"161.1 T/h",
"avgopen_close_time":123298,
"ticket_time":"27.1 T/h",
"stats":{
"time":1498768200087,
"newest_ticket":1498768189000,
"closed_tickets":2200,
"open_tickets":13,
"active_workers":3
},
"avg_paid_tickets":64.55,
"avg_afterservice_tickets":35.45
}
This is the PHP code I tried to get the names of the worker but this doesn't work.
<?php
$string = file_get_contents("example.json");
$json = json_decode($string, true);
echo $json['address'];
foreach($json->workers->new as $entry) {
echo $entry->worker;
}
?>
If I try it like here below it works but then I've got to change the code everytime another employee starts.
echo $json['workers']['mark']['closed_tickets'];
<?php
$string = file_get_contents("example.json");
$json = json_decode($string, true);
foreach($json['workers'] as $entry){
echo $entry['worker'] . " has " . $entry['open_tickets'] . " tickets" . "\n";
}
?>

How to output JSON onto page using PHP

Okay so I'm playing around with php at the moment. I have a .html file and a .php file. The .html file contains a textarea. The .php file contains some functions that messes around with the user's typed json string. I know how to output php onto the webpage. I want to output the WHOLE json script onto the textarea. Basically in the .php file, I want to convert the json to a string, and pass that string into the .html's textarea.
This is the json:
{
"destination_addresses" : [ "New Town, Uckfield, East Sussex TN22 5DJ, UK" ],
"origin_addresses" : [ "Maresfield, East Sussex TN22 2AF, UK" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "3.0 mi",
"value" : 4855
},
"duration" : {
"text" : "22 mins",
"value" : 1311
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I tried using json_encode() but got errors because of the quotations marks being out of place so Im wondering if theres an easier way to convert the whole json to a string .
If you are not getting the line returns and tabs for formatting you can use my pretty json print function, which will add tabs and line returns to the json data.
function PrettyJson($json) {
$tc = 0; //tab count
$r = ''; //result
$q = false; //quotes
$t = "\t"; //tab
$nl = "\n"; //new line
for($i=0;$i<strlen($json);$i++){
$c = $json[$i];
if($c=='"' && $json[$i-1]!='\\') $q = !$q;
if($q){
$r .= $c;
continue;
}
switch($c){
case '{':
case '[':
$r .= $c . $nl . str_repeat($t, ++$tc);
break;
case '}':
case ']':
$r .= $nl . str_repeat($t, --$tc) . $c;
break;
case ',':
$r .= $c;
if($json[$i+1]!='{' && $json[$i+1]!='[') $r .= $nl . str_repeat($t, $tc);
break;
case ':':
$r .= $c . ' ';
break;
default:
$r .= $c;
}
}
return $r;
}
Then you just echo it
echo '<textarea>'.PrettyJson( $json ).'</textarea>';
Basically what it does is given json string like this
{"one":[1,2,3],"two":{"three":3}}
It will make it like this ( or similar )
{
"one" : [1,2,3],
"two" : {
"three" : 3
}
}
Typically I just use it for display so I am not sure right off if you need to remove the white space when decoding it.
If the PHP holds also the HTML then just use htmlspecialchars() to escape the special characters that would be problematic between the <textarea> tag.
Small example of a PHP file:
<?php
// Get the json value from a previous POST or set a default value.
$json = isset($_POST['json']) ? $_POST['json'] : '{
"destination_addresses" : [ "New Town, Uckfield, East Sussex TN22 5DJ, UK" ],
"origin_addresses" : [ "Maresfield, East Sussex TN22 2AF, UK" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "3.0 mi",
"value" : 4855
},
"duration" : {
"text" : "22 mins",
"value" : 1311
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}';
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div><!-- because form elements should not be direct childs of the form -->
<label for="json">Type your JSON:</label>
<br />
<textarea name="json" rows="25" cols="84"><?php echo htmlspecialchars($json); ?></textarea>
<br />
<br />
<input type="submit" value="submit" />
</div>
</form>

Categories