PHP JSON_encode output - php

This is my first time using PHP and I am making a script that will output text in JSON format. However I am encountering problems with the formatting.
Can someone explain why my browser renders the following code as..
"1", 'b' => "2", ), array( 'a' => "1", 'b' => "2", 'c' => "3", ) ) ); ?>
instead of something like this?
[
[ { "a" : "1" }, { "b" : "2" } ],
[ { "a" : "1" }, { "b" : "2" }, { "c" : "3" } ]
]
Code:
<body>
<?php
echo json_encode(
array(
array(
'a' => "1",
'b' => "2"
),
array(
'a' => "1",
'b' => "2",
'c' => "3"
)
)
);
?>
</body>

Your code is correct, but the setup doesn't seem right. Your PHP code isn't evaluated. What happens if you put nothing but
<?php phpinfo(); ?>
into your file? Does it show only the code or a long table with all kinds of infos? If it's the former, then you need to find out how to get your webserver to interpret the embedded PHP code before sending it to your browser.

Save file as YourFile.php
Run on Xampp server like localhost/yourFile.php , not like D://File....bla bla

You saved your file as html.
Change your file from FileName.html to FileName.php

Related

PHP convert similar names variables to json

I'm getting via url querystring variables like:
myserver_state=1&myserver_running=2&myserver_mem=3
Currently i'm adding to an existing json like:
{
"key1": "1",
"key2": "2",
"key3": "3",
"myserver_state": "1",
"myserver_running": "2",
"myserver_mem": "3"
}
And i really want it like this:
{
"key1": "1",
"key2": "2",
"key3": "3",
"myserver": {
"state": "1",
"running": "2",
"mem": "3"
}
}
I'm using this to load them:
$formdata = array(
'state'=> $_POST['state'],
'uassip'=> $_POST['uassip'],
'uassipport'=> $_POST['uassipport'],
'c_uacminrtpport'=> $_POST['c_uacminrtpport'],
'c_uacmaxrtpport'=> $_POST['c_uacmaxrtpport'],
'c_cps'=> $_POST['c_cps'],
'c_totalcalls'=> $_POST['c_totalcalls'],
'c_maxchannels'=> $_POST['c_maxchannels'],
'c_duration'=> $_POST['c_duration'],
'c_to'=> $_POST['c_to'],
'c_uacxml'=> $_POST['c_uacxml']
);
echo "fromdata: <br>"; echo var_dump($formdata) . "<br><hr>";
if(file_put_contents('testconfig.json', json_encode($formdata) )) echo 'OK';
else echo 'Unable to save data in "testconfig.json"';
Many thanks!
EDIT:
following comments i tried:
status.php?server1[current_state]=10
this actually works to:
"c_uacxml": "telnyx-uac-invite-ok.xml",
"server1": {
"current_state": "10"
}
}
Which is great, BUT, if i then want to add an element like this:
status.php?server1[current_mem]=1
This actually REPLACES the whole server1
"c_uacxml": "telnyx-uac-invite-ok.xml",
"server1": {
"current_mem": "10"
}
}
and i lose the already existing current_state
Just use multidimensional array within your URL like:
test.php?key1=1&key2=2&myserver[state]=1&myserver[running]=2&myserver[mem]=3
so easy script
<?php
echo '<pre>';
echo json_encode($_GET, JSON_PRETTY_PRINT);
will give you
{
"key1": "1",
"key2": "2",
"myserver": {
"state": "1",
"running": "2",
"mem": "3"
}
}
of course, if required you can use also POST request with the same naming rules.
in order to create a nested JSON object, you need to create an array within an array.
E.g.
$example = [
'key1' => 'foo',
'key2' => 'bar',
'key3' => [
'subkey1' => 'foo',
'subkey2' => 'bar',
],
];
When running it through json_encode(), it will result in
{
"key1": "foo",
"key2": "bar",
"key3": {
"subkey1": "foo",
"subkey2": "bar"
}
}
Also it's not necessary to load form data like this –
$formdata = [
'state' => $_POST['state'],
'uassip' => $_POST['uassip'],
'uassipport' => $_POST['uassipport'],
'c_uacminrtpport' => $_POST['c_uacminrtpport'],
'c_uacmaxrtpport' => $_POST['c_uacmaxrtpport'],
'c_cps' => $_POST['c_cps'],
'c_totalcalls' => $_POST['c_totalcalls'],
'c_maxchannels' => $_POST['c_maxchannels'],
'c_duration' => $_POST['c_duration'],
'c_to' => $_POST['c_to'],
'c_uacxml' => $_POST['c_uacxml'],
];
Since the $_POST already contains a structure that you are trying to recreate. You can simply assign the post data to a new varaible.
On another note, I highly recommend you to check out PSR PHP standards, they will greatly help to improve code readability and your code structure :) https://www.php-fig.org/psr/

how to create a costume layout for json data returned from mysql database for UTF-8 characters in php

I am trying to create a json representation of mysql data in a restful webservice using php. my returned json should look something like this:
"worktypes" :
[
{
"id" : "1",
"name" : "نوع 1",
"isactive" : "true"
},
{
"id" : "2",
"name" : "نوع 2",
"isactive" : "false"
}
]
one of my options was to iterate through my result records and echo each line by hand. It was working until I reached utf8 characters shown above (like 'نوع 1') and instead of ending up with something like \u00d9\u0086\u00d9\u0088\u00d8\u00b9 I got unreadable symbols like ÃÂÃÂù çÃÂÃÂ.
If I could use json_encode somehow to create this layout, it would automatically solve this problem;But I don't know how to create such a structure in php that its json_encoded string represents my desired layout.
My other option is to somehow encode these characters myself. But I don't know how to do that either.
Could anyone help me with my problem?
UPDATE: I use a simple echo in my webservice when I get unusual characters like :
$result = array("1" => "نوع 1")
echo $result;
//results in 'ÙÙع 1' when called using webservice
The equivalent PHP array to what you have given is:
$x = array(
"worktypes" => array(
array(
"id" => "1",
"name" => "نوع 1",
"isactive" => "true"
),
array(
"id" => "2",
"name" => "نوع 2",
"isactive" => "false"
)
)
);
You can then use json_encode.
Note that you may still see escaped characters, but the browser should be able to handle unescaping them when it parses the JSON.

PHP - How to create JSON with JSON object inside [duplicate]

This question already has answers here:
create nested JSON object in php?
(7 answers)
Closed last year.
I have to comunicate with some API which expect JSON.
Until now I was fine because I needed just simple json so I just create array like this:
$data = array (
"firstName" => "TEXT1",
"lastName" => "TEXT2",
"license" => "TEXT3",
"password" => "TEXT4",
"username" => "TEXT5"
);
And after that just simple
$data_string = json_encode($data);
So final JSON looks like:
{
"firstName": "TEXT1",
"lastName": "TEXT2",
"license": "TEXT3",
"password": "TEXT4",
"username": "TEXT5"
}
However now I have to change it a bit and I am confuse, my new JSON shoud looks like:
{
"contact": {
"city": "New Yourk",
"email": "my#mail.com",
"phone": "777888999",
"postCode": "07101",
"street": "Street N. 12"
},
"enabled": true,
"firstName": "Robert",
"lastName": "Exer",
"username": "login#login.com",
"license": "text",
"password": "text"
}
As you can see it is basicly just added contact part. I was thinking how I can do this but only think I found was something like to insert array to existing $data array and then json_encode this but this will not give me a contract: at start.
Of course there is possible to do it some other way like create one json and then another and hardly connect string and so on. But i believe there have to be some better way how to do things like this.
I apprciate any advise:)
Just put an array in the value of contact:
$data = array(
'contact' => array(
'city' => 'New York',
'email' => 'my#mail.com',
//...
),
'enabled' => true,
'firstName' => 'Robert',
'lastName' => 'Exer',
//...
);
$data_string = json_encode($data);
An array can contain another array, which will be encoded as a separate object inside the previous object:
$data = array (
"contact" => array(
"city" => "New Yourk",
"email" => "my#mail.com",
"phone" => "777888999",
"postCode" => "07101",
"street" => "Street N. 12"
),
"enabled": true,
.. etc
);

Creat json data file for gallery file with php

I know this question was asked already for couple times, I've seen the answers but it already helped me a lot, but i need to solve one more problem regarding to this.
So the question is:
I need to build json file with php.
Here how looks my json file that i need:
{
"fashion":[
{
"alt":"Alisa",
"src":"img/fashion/Alisa/kubik.jpg",
"class":"albumItem",
"id":"FashionAlbum001",
"itemNum":0,
"album":[
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa1.jpg"
},
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa5.jpg"
},
{
"alt":"albumImg1",
"src":"img/fashion/Alisa/alisa7.jpg"
}
]
},
{
"alt":"2-Addis",
"src":"img/fashion/2-Addis/kubik.jpg",
"class":"albumItem",
"id":"FashionAlbum002",
"itemNum":1,
"album":[
{
"alt":"albumImg1",
"src":"img/fashion/2-Addis/addis1.jpg"
},
{
"alt":"albumImg4",
"src":"img/fashion/2-Addis/addis4.jpg"
}] } ] }
and so on...
I can't find out how to make a list of images inside each album
This is a php function a have
function buildJson(){
$json = json_encode(array(
"Fashion" => array(
"alt" => "Alisa",
"src" => "img/fashion/Alisa/kubik.jpg",
"id" => "FashionAlbum001",
"itemNum"=>"1",
"album"=>array(
"src"=>"img/fashion/Alisa/alisa1.jpg",
),
array(
"src"=>"img/fashion/Alisa/alisa5.jpg",
),
array(
"src"=>"img/fashion/Alisa/alisa7.jpg",
),
)
));
echo $json;
}
but I get json like this one:
{
"Fashion": {
"0": {
"src": "img/fashion/Alisa/alisa2.jpg"
},
"1": {
"src": "img/fashion/Alisa/alisa3.jpg"
},
"alt": "Alisa",
"src": "img/fashion/Alisa/kubik.jpg",
"id": "FashionAlbum001",
"itemNum": "0",
"album": {
"src": "img/fashion/Alisa/alisa1.jpg"
}
}
}
How is it possible to fix it?
Thank you!
Please pay more attention to the code you're writing :) Try to decode correct version of your json file and compare it to one you wrote. You should see some differences.
Your problem ir what follows after album key. You are assigning array with only one value to it instead of assigning array of arrays.
This is the way to go:
"album" => array(
array("src" => "img/fashion/Alisa/alisa1.jpg"),
array("src" => "img/fashion/Alisa/alisa5.jpg"),
array("src" => "img/fashion/Alisa/alisa7.jpg"),
),
you trouble in nesting album array
fixed code
function buildJson(){
$json = json_encode(
array(
"Fashion" => array(
"alt" => "Alisa",
"src" => "img/fashion/Alisa/kubik.jpg",
"id" => "FashionAlbum001",
"itemNum"=>"1",
// nesting error here
"album"=> array(
array("src"=>"img/fashion/Alisa/alisa1.jpg"),
array("src"=>"img/fashion/Alisa/alisa5.jpg"),
array("src"=>"img/fashion/Alisa/alisa7.jpg")
)
)
)
);
echo $json;
}

How to output this json {},{} with php?

I was unable to output this:
[{"title":"London","foo":"bar"},{"title":"Istanbul","foo":"bar"}]
I cannot make comma here: },{
I can output this [{"title":"London","foo":"bar"}] but not the first example.
This will produce the desired output:
$data = array(
array("title" => "London",
"foo" => "bar"
),
array("title" => "Istanbul",
"foo" => "bar"
)
);
echo json_encode($data);
Make sure you create your arrays correctly. For more information have a look at the documentation for json_decode.

Categories