Decode Json Object from a url in php coming from a user - php

hey i am making an android app where user's request in the format of json . Their request will look like this..
JSONObject j = new JSONObject(createJson());
String url ="http://codemoirai.esy.es/test.php?UserDetails="+j;
Where j = {"Email":"code#gmail.com","Username":"xyz","Password":"xyz"}
This is what I will be sending to the test.php , i want to know how i can fetch this data and display it using php.
<?php
require "init1.php";
$jsonObject = $_GET["UserDetails"];
$obj = json_decode($jsonObject);
$email = $obj->Email;
$password = $obj->Password;
.......
echo $email; //Everthing i fetch from jsonObject is null. Why?
?>
ThankYou, is it correct how i am fetching in php??

In test.php you can catch the data with $_GET['UserDetails'] then decode it with json_decode($_GET['UserDetails')
Then you can iterate it with a foreach loop
Example:
if(isset($_GET['UserDetails'])) {
$details = json_decode($_GET['UserDetails']);
foreach($details as $key => $val) {
echo $key.' = '.$val;
}

Related

How to get the value from json with PHP

How can I get the source, title, issn, author, ... from a json file: JSON file
We tried with:
$new_pmid = $_POST['new_pmid'];
$api_json_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=".$new_pmid."&retmode=json";
$json = file_get_contents($api_json_url);
$data = json_decode($json, TRUE);
echo $header[0]->result->$new_pmid->title;
....
But nothing happen...
Can you give me the solution for the json file (generated from pubmed database).
Thank you.
You didn't use the $data variable, which stored the decoded data
You decode JSON into $data as array
$title = $data['result'][$new_pmid]['title'];
$issn = $data['result'][$new_pmid]['issn'];
$authors = $data['result'][$new_pmid]['authors'];
--Update--
To get $authors name ,authtype ,... use foreach loop:
foreach($authors as $author){
$name = $author['name'];
$authtype = $author['authtype'];
$clusterid = $author['clusterid'];
}

Php JSONArray decoding and performing Database Operation

I'm sending a JsonArray from my android application as this:
final JSONArray data = new JSONArray();
try{
for(int i = 0; i<contactsList.size(); i++){
JSONObject jobj = new JSONObject();
ObjectContacts ob = contactsList.get(i);
jobj.put("contactid", ob.getContact_id());
jobj.put("mobile", ob.getNumber());
data.put(jobj);
}
}
And the resulting Array that my server receive.
[
{"contactid":"3","mobile":"(545) 454-5445"},
{"contactid":"1","mobile":"(880) 939-5212"},
{"contactid":"2","mobile":"822895456165"}
]
I need to fetch mobile numbers from this array and perform a Db Operation to look if this mobile number exist or not. How can I access each mobile and perform a Query? The query will consist of looking for mobile number existence and if it's true, it will fetch the name belonging to the mobile number and finally return an array back to the mobile application in JSONArray format which will consist of contact id, mobile, status(Yes or No), name.
Time won't be an issue but sometimes the array may contain 300-400 mobile number depending on user's contact.
Update
Here's the new Php Code that I implemented:
$app->post('/getcontacts', function () use ($app) {
//Verifying the required parameters
verifyRequiredParams(array('data'));
//Creating a response array
$response = array();
//reading post parameters
$data = $app->request->post('data');
$data_array = json_decode($data);
foreach ( $data_array as $obj ) {
$res = array();
$db = new DbOperation();
$r = $db->checkContactExist($obj->mobile);
if($r){
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'yes';
$res["image_small"] = $db->getImageSmall($obj->mobile);
} else {
$res["contactid"] = $obj->contactid;
$res["mobile"] = $obj->mobile;
$res["name"] = $obj->name;
$res["status"] = 'no';
$res["image_small"] = '';
}
}
$response["error"] = false;
$response["message"] = json_encode($res);
echoResponse(201, $response);
});
The response I get from server:
{"contactid":"3","mobile":"(943) 101-9713","status":"no","image_small":""}
While there should be three contacts, it could only read one.
If I just send the incoming data back to application through echo to check whether all the contacts is coming or not, then it works correct. Maybe in the loop I'm adding detail about only one contact.
Second Update
Have solved the issue by putting :
$final_res = array();
and in foreach loop
$final_res[] = $res;
thus sending this back:
json_encode($final_res);
That string will convert to a PHP array of objects, after using json_decode() on the string.
So this is how you process it
<?php
$json_string = '[
{"contactid":"3","mobile":"(545) 454-5445"},
{"contactid":"1","mobile":"(880) 939-5212"},
{"contactid":"2","mobile":"822895456165"}
]';
$json_array = json_decode($json_string);
foreach ( $json_array as $obj ) {
echo $obj->contactid . ' - ' . $obj->mobile . PHP_EOL;
}
Result:
3 - (545) 454-5445
1 - (880) 939-5212
2 - 822895456165
You should be able to take this and add any database access around this simple code

Error while trying to read posted json data in php

I have the following problem. When i am trying to read some json data that are posted from an html page, i'm facing with the following error "Trying to get property of non-object on line".
Jquery script to create the json
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
Jquery for posting to php
$.post("page.php",{jsonData: JSON.stringify(json),
customer: $("#cusID").val()},function(data){});
PHP file
$json = json_decode($_POST['jsonData']);
foreach($json as $value){
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
Thanks in advance.
Thereafter:
var json = {"data":[]};
json.data.push({serialNumber: $serialNumber, xreosi: $xreosiToPost,
forma: $forma, apolia: $apolia});
You have:
Object[data][0] = array('serialNumber' => ...);
Need:
$json = json_decode($_POST['jsonData'][0]);
or
$json = json_decode($_POST['jsonData']);
foreach($json as $row){
foreach($row as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}
}
json_decode without second parameter returns result as php object. You have to pass true as second parameter. Also your data are in $json['data'], not $json:
$json = json_decode($_POST['jsonData'], true);
foreach($json['data'] as $value) {
$serialNumber = $value->serialNumber;
echo $serialNumber;
}

android, php, parsing JSON in php file sent from android

i have this JSON
{
"count":"3",
"num":"1",
"array":[
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":0
},
{
"id":"a_a",
"amount":56,
"duration":"0:12",
"time":1234566,
"type":1
}
]
}
created it in android and send it by **HttpPost**
, i've tried a lot of ways to get the data in the php, my php file is this:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn,true);
$count = $json_data->{'count'};
$num = $json_data["num"];
$response["data"]=$count;
$response["data2"]=$num;
// echoing JSON response
echo json_encode($response);
?>
but $count and $num always returns null, any help please, and thanks.
$json_data = json_decode($josn,true);
this returns an array, not an object (which you are using later in the code). Use this to convert the json string to an object:
$json_data = json_decode($josn);
Or you could just use arrays, in which case your code should look like:
<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))
$josn = file_get_contents("php://input");
$json_data = json_decode($josn, true); // using true to get array
$count = $json_data["count"]; // accessing array values as normal
$num = $json_data["num"]; // accessing array values as normal
$response["data"] = $count; // instead of setting $count first you could just add
$response["data2"] = $num; // the json_data array values directly to the response array
// echoing JSON response
echo json_encode($response);

Retrieve all values in my loop and format it to json

I'm trying to build a page which queries my database and then formats output so another webservice/page can access the data.
Ideally I wanted to explore having the data in JSON format, but that is not working. The other problem I have which is more major than the JSON not working is, if I have 3 records in $reportsResult, only the last one is displayed.
Anyone with some help please. Oh do I also need to print_r for the external webpage to retrieve the data or is there a better way?
class Pupil {
public $FirstName = "";
public $LastName = "";
}
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
}
json_encode($Pupil);
OK managed to figure out how how to get all records from the loop, but its still not displaying in json format when I do a print_r - am I missing something?
$AllPupils = array();
foreach($reportsResult->getRecords() as $reportRecord)
{
$Pupil = new Pupil();
$Pupil->FamID = $reportRecord->getField('FName');
$Pupil->ChildName = $reportRecord->getField('SName');
array_push($AllPupils, $Pupil);
}
json_encode($AllPupils);
Everytime your foreach loop starts again, it will override your $Pupil variable.
Try an array instead:
$Pupil = array()
$i = 0;
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil[$i] = new Pupil();
$Pupil[$i]->FirstName = $reportRecord->getField('FName');
$Pupil[$i]->LastName = $reportRecord->getField('SName');
$i++;
}
echo json_encode($Pupil);
Edit: mikemackintosh's solution should also work and could be a little bit faster (depending on the size of your foreach loop).
To display the results you need to echo your data (not only json_encode).
You will probably run into issues since json_encode wont handle the whole object. for that, you may want to serialize the $Pupil object.
Something like below may work for you though. It will assign the values to a returned array, which will allow json_encode to execute gracefully:
class Pupil {
public $FirstName = "";
public $LastName = "";
public function getAttr(){
return array("FirstName" => $this->FirstName, "LastName" => $this->LastName);
}
}
$json = array();
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
$json[] = $Pupil->getAttr();
}
echo json_encode($json);
I am not sure why you have that class defined, but you know what in your for each have something like
foreach ($reportsResult->getRecords() as $key => $record) {
$data[$key]['firstname'] = $record->getField('Fname');
$data[$key]['lastname'] = $record->getField('Sname');
}
And then you can check the final array using print_r
and while output you can simply do a print json_encode($data) and it will give you a json string of all the items in the data array.
In php (at least), json_encode takes an array as parameter.
Therefore you should add a constructor to your class
function __construct($first, $last)
{
this.$FirstName = $first;
this.$LastName = $last;
}
and one for getting the full name as an array, ready to be jsoned
function getNameArray()
{
$nameArray = array();
$nameArray['firstName'] = this.$FirstName;
$nameArray['lastName'] = this.$LastName;
return $nameArray;
}
then in that foreach you build another array with all the pupils
$pupils = array();
foreach (bla bla)
{
$first = $reportRecord->getField('FName');
$last = $reportRecord->getField('SName');
$Pupil = new Pupil($first, $last);
array_push($pupils, $pupil.getNameArray());
}
finally, you have everything preped up
json_encode($pupils);
I'm sure there's other ways to debug your stuff, I use print_r mainly also.

Categories