How to extract the JSON encoded POST parameters in PHP - php

I have passed JSON encoded parameters by POST which we have captured and decoded in another PHP file. I have used the following code to do that.
$entityBody = file_get_contents('php://input');
$entityBody = json_decode($entityBody, true);
I have passed the JSON encoded parameters as follows:
{
"id": "5",
"name": "abcd",
"imei": "1234"
}
Here my code works perfectly fine. However, I want to get all the parameters into a single object so that we can store them efficiently because otherwise there will be too many ifs and elses to get each parameter. So I have encoded the parameters as follows:
device = {
"id": "5",
"name": "abcd",
"imei": "1234"
}
But it is not working. Being new to JSON and PHP I do not know how to handle such cases. How can I achieve this?

use json_decode($_POST['device'], true) since your actually passing a parameter called 'device' to the php file.

You should pass json objects as follow:
{"device" : {
"id": "5",
"name": "abcd",
"imei": "1234"
}}
or if you have an array of devices
{"device" : [{
"id": "5",
"name": "abcd",
"imei": "1234"}
]}

Related

Filter response from json with php

for example, i have json result like this
[
{
"title": "x1",
"url": "domain.com"
},
{
"title": "x2",
"url": "example.com/"
},
{
"title": "x3",
"url": "site.com/cam"
},
]
The result of json will be randomly, i want to scrape ['x']['url'] path from that json, but the value of ['url'] must be "site.com/cam", and as you know, the results from json will change randomly, so I do not know which json path with value is "site.com/cam".
is there any suggestion? Thank you
Try this
$index = array_search('site.com/cam',array_column(json_decode($json),'url'));
Sandbox
https://3v4l.org/72tsZ
Output
$index = 2
Oh and there is a typo in your JSON
}, <-- remove comma here.
]

How to fetch PHP database values in Json?

I have to create Matrix tree view in my project. So am plan to use json. My question is how to fetch PHP values in Json ?. I did static matrix tree but i want dynamic. Thank you for advance.
My code is following:
<?php
include('db.php');
$select = mysql_query("select * from table1");
while($row = mysql_fetch_array($select))
{
?>
{
"name": "A", // Here database values come $row['name'];
"children": [
{
"name": "B",
"children": [
{"name": "B-1"}
]
},
{
"name": "C",
"children": [
{"name": "C-1", "size": 1082},
{"name": "C-2", "size": 1681}
]
},
{
"name": "D",
"children": [
{
"name": "D-1",
"children": [
{"name": "D-1 1", "size": 1302},
{"name": "D-1 2", "size": 6703}
]
},
{"name": "D-2", "size": 16540}
]
}
]
}
<?php
}
?>
In this example Im using the mysqli driver. Do not use the mysql driver.
you just need to convert your output data into a json object.
Its possible to extract all the rows at once which is going to give you a marginally less overhead.
$data = mysqli_fetch_all($select); // returns everything in an associative array
$json_data = json_encode($data); // converts that array to json.
if you need specific keys, then manipulate your query to rename columns as necessary eg.
$query = "select name as firstname from ....";
You can just retrieve data from your database and store it in arrays like you normally would. Then call PHP's built in function json_encode() to transform your PHP array into json (assuming your PHP array is well formed (which should be the case if you get it out of a database)).
You could argue that this is slower because you're iterating over the data twice instead of once, but it shouldn't matter, the complexity remains the same.

extracting json in php

From MySQL row, I have this json formatted data:
$row['details'] =
{
"previous_employer":[
{"employer":"string1","address":"address1"},
{"employer":"string2","address":"address2"},
{"employer":"string3","address":"address3"}],
"profile":[
"firstname":"John",
"lastname":"Adams",
"gender":"male",
"age":"35",
"contact":"123456789"]
}
I want to extract employer and address on the previous_employer array of objects,
but when I do this:
$json = json_decode($row['details'],true); //decode into array
foreach($json['previous_employer'] as $d){
echo "employer:".$d['employer']."<br>address:". $d['address']."<br>";
}
it gives me an error of
Warning: Invalid argument supplied for foreach()
How can I fix this? Pls advise.. thanks!
You JSON is invalid, "profile" must be
An Object:
"profile": {
"firstname": "John",
"lastname": "Adams",
"gender": "male",
"age": "35",
"contact": "123456789"
}
or an Array of Object (here his length == 1)
"profile": [{
"John",
"Adams",
"male",
"35",
"123456789"
}]
or a Simple Array (not associative array/map)
"profile": [
"John",
"Adams",
"male",
"35",
"123456789"
]
Now, your posted code will work as a charm without any modifications ... :)
json_decode() does not necessarily succeed (just imagine you feed it with complete garbage, why should it return something?). You need to do the following error checking:
Verify its return value:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
If valid data can be expected to return null some times, call json_last_error() and check whether it's JSON_ERROR_NONE.
Last but not least, you can explore any variable with var_dump(). You don't need to make assumptions about its content.

How to parse JSON from Url and named array

I'm trying to parse a JSON string from a url with a named array.
Ex.
{
"Attendees": [{
"user_id": "123",
"first_name": "Jim",
"last_name": "Bill",
"email": "jsfbsjkd#aim.com",
"title": "Admin",
"business_unit": "",
"area": ""
}]
}
i've tired this:
$(document).ready(function(){
$.getJSON('http://localhost/testJSON/json.php', function(data){
alert(data.user_id); // 1 });
});
but it's creating Object Object. Any help is appreciated.
Instead of alert(), try this:
console.log(data.Attendees[0].user_id);
Then using developer tools in Chrome (or another developer friendly browser), check the console for the result here.

Get JSON objects in PHP, not array

Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}
I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.
You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num
First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...

Categories