browse a JSON and fill PHP variables [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
i work on project, where there are server that send to my php application json data and then i put it in database.
I receive a POST request from the server and i can get json with this :
receive_json.php:
$payload = file_get_contents('php://input');
and there is the form of the JSON:
{
"applicationID": "123",
"applicationName": "temperature-sensor",
"deviceName": "garden-sensor",
"devEUI": "0202020202020202",
"rxInfo": [
{
"gatewayID": "0303030303030303", // ID of the receiving gateway
"name": "rooftop-gateway", // name of the receiving gateway
"time": "2016-11-25T16:24:37.295915988Z", // time when the package was received (GPS time of gateway, only set when available)
"rssi": -57, // signal strength (dBm)
"loRaSNR": 10, // signal to noise ratio
"location": {
"latitude": 52.3740364, // latitude of the receiving gateway
"longitude": 4.9144401, // longitude of the receiving gateway
"altitude": 10.5, // altitude of the receiving gateway
}
}
],
"txInfo": {
"frequency": 868100000, // frequency used for transmission
"dr": 5 // data-rate used for transmission
},
"adr": false, // device ADR status
"fCnt": 10, // frame-counter
"fPort": 5, // FPort
"data": "...", // base64 encoded payload (decrypted)
"object": { // decoded object (when application coded has been configured)
"temperatureSensor": {"1": 25},
"humiditySensor": {"1": 32}
}
}
i'm new user of JSON, so i put directly the text JSON to my database like this :
$payload = file_get_contents('php://input');
$req = $bdd->prepare( '
INSERT INTO nods(payload)
VALUES (:payload);
' );
$req->execute(array('payload' => $payload));
the result :
I would like to browse " $payload " and put the information in php variables like:
$applicationID = .... ;
$rxInfo[] = .... ;
i already try somthing like "foreach" but i could not succes, can you help me please, thanks :).
Best regard,
DIDOUH JAWAD

You can use json_decode to get a PHP array representation of the JSON
$array = json_decode($payload, true);
var_dump($array);
http://php.net/manual/en/function.json-decode.php

Related

PHP, split received POST data after few words or sentences

I am able to send JSONObject data from my application to server with PHP. I am also able to read the data. But now I want to send the data with a USER ID and type of data in the first two sentences. I am able to send this data from my application.
But I am not experienced with working on PHP and I dont know how to split this data after reading USER id and the type I have received and to store the rest of data separately ( and should be stored as json data with USER ID as filename).
Currently I am using the following to just save the
<?php
$content = file_get_contents('php://input');
$data = json_decode($content, true);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
if(!is_array($data)){
throw new Exception('Received content contained invalid JSON!');
}
echo "Data Received";
?>
This is the json data format,
[{ "increment_id": "1", "uuid": "43c87b6e-4fd5-4f1b-9bba-3e512eb4787a", "xValue": "39.0", "yValue": "72.0", "inputTime": "Thu Mar 08 15:38:58" }]
I also want to attach user id with it, which I am able to attach and send it to server, but I cannot use json decode now as the format changes to re encode if I give a userid with it in the first sentence . So after attaching userid and type the data looks like this
UserID Type [{ "increment_id": "1", "uuid": "43c87b6e-4fd5-4f1b-9bba-3e512eb4787a", "xValue": "39.0", "yValue": "72.0", "inputTime": "Thu Mar 08 15:38:58" }]
What sentences? Send it where? Its far from clear what you are asking.
I dont know how to split this data
We don't either. What do you mean by split? That implies there's going to more than one data item - where do you want to split it? What do you want to do with the 2 parts?
should be stored as json data with USER ID as filename
It is very unlikely that it should be stored where you are currently putting it - particularly when you are applying no validation to the data you saved.
Consider (and note the differences with your script):
<?php
define("DEST_DIR", "/not/in/your/document/root/");
$content = file_get_contents('php://input');
$data = json_decode($content, true);
if (isset($data['USER'])) {
$filename=basename($data['USER']);
$filename="data_" . array_shift(explode('.', $filename) . 'json';
file_put_contents(DEST_DIR . $filename);
print json_encode(array('result'=>'success'));
} else {
header("Bad Request", true, 400);
print json_encode(array('result'=>'bad input data');
}

Empty $_POST Array parsing JS Object to PHP via JSON

I assume some of you might be already rolling their eyes since my topic has been dealt with so often in this forum. However, I haven't found any solution yet in this forum.
I want to parse a JS Object to a receiving PHP Site via JSON. I already read numerous times about the right parameters for the XMLHttpRequest-Header and its impact on the PHP part. I tried the very same solutions given in several other forums, but IT SIMPLY DOESN'T WORK for me. I've been working on this whole issue for four month now. I really need some advice.
Here is my JSON encoding JS Script:
function saveToDB(knotItems) {
var txtobj = knotItems;
var json = JSON.stringify(txtobj);
var url = "http://localhost/projektplaner/tools/DBConnection/writeFileToDB.php";
rq = new XMLHttpRequest();
rq.open("post", url, true);
rq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
rq.send("project=" + json);
rq.onreadystatechange = window.open(url);
}
This is the JS-generated object array knotItems after being stringified by JSON:
[{
"rank": 1,
"name": "Baugrube",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "19.5.2016",
"faz_timestamp": 1463680336402,
"d": "2",
"parallelTask": "seriell",
"fez": ["2016-05-21T17:52:16.402Z", "21.5.2016", "NaN2"],
"fez_dateObj": "2016-05-21T17:52:16.402Z",
"fez_string": "21.5.2016"
}, {
"rank": 2,
"name": "Kellerwände",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "21.5.2016",
"faz_timestamp": 1463853136402,
"d": "4",
"parallelTask": "seriell",
"fez": ["2016-05-25T17:52:16.402Z", "25.5.2016", "NaN4"],
"fez_dateObj": "2016-05-25T17:52:16.402Z",
"fez_string": "25.5.2016"
}, {
"rank": 3,
"name": "Kellerdecke",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "25.5.2016",
"faz_timestamp": 1464198736402,
"d": "5",
"parallelTask": "seriell",
"fez": ["2016-05-30T17:52:16.402Z", "30.5.2016", "NaN5"],
"fez_dateObj": "2016-05-30T17:52:16.402Z",
"fez_string": "30.5.2016"
}]
The reason I post the variable content is to show that all object keys are in double quotes, as required by PHP's json_decode.
This is my PHP receiving script:
if(isset($_POST['project']))
{
echo json_decode($_POST['project'],true);
}
else
{
echo "Keine Daten"; // No Data
}
This is the parameter payload that can be seen via Firebug analysis:
project:"[{"rank":1,"name":"Baugrube","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"19.5.2016","faz_timestamp":1463680336402,"d":"2","parallelTask":"seriell","fez":["2016-05-21T17:52:16.402Z","21.5.2016","NaN2"],"fez_dateObj":"2016-05-21T17:52:16.402Z","fez_string":"21.5.2016"},{"rank":2,"name":"Kellerwände","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"21.5.2016","faz_timestamp":1463853136402,"d":"4","parallelTask":"seriell","fez":["2016-05-25T17:52:16.402Z","25.5.2016","NaN4"],"fez_dateObj":"2016-05-25T17:52:16.402Z","fez_string":"25.5.2016"},{"rank":3,"name":"Kellerdecke","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"25.5.2016","faz_timestamp":1464198736402,"d":"5","parallelTask":"seriell","fez":["2016-05-30T17:52:16.402Z","30.5.2016","NaN5"],"fez_dateObj":"2016-05-30T17:52:16.402Z","fez_string":"30.5.2016"}]"
HTTP Status Code is always 200 (OK).
And this is what I get from the PHP File.
Notice: Undefined index: project in C:\xampp\htdocs\projektplaner\tools\DBConnection\writeFileToDB.php on line 7
Keine Daten
I don't want to sound melodramatic or anything, but I'm about to go ape. I just can't see what the hell is wrong. Could it be a Server configuration issue?
I really, really appreciate your help.
Thank you very much in advance.

Receive array of numbers in php (JSON)

I would like to get an array from my JSON in php.
This way I get the JSON string from URL in my android application:
JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", paramstodb);
To receive [phone=123] in php I use this:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
That is working for one phonenumber, but now I need more than one phonenumber.
The data in Logcat (reported with "Log.d("to php: ", paramstodb.toString())" ) is displayed as:
to php:﹕ [phone=[0127361744, 0132782422, 0137173813, 0142534646, 0123617637435, 013391339494, 01383375633, 013878942423, 013891748422, 01389487285, 014434354234, 01848481371, 018831789414, 021238133441231, 021371689411, 02183718454, 123, 456]]
How can I get all numbers in an array in php?
This is not working so far:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
$phpArray = json_decode($phone, true);
I hope you can help me again ;-)
If the JSON input to the PHP script really is this JSON
{ "phone": [ "123", "456", "789"] }
then PHP's json_decode should handle it without problems.
You can try this code to see it's actually working and use it to detect where something goes wrong:
// original JSON to send from the client
$jsonString = '{ "phone": [ "123", "456", "789"] }';
// build a query string with the JSON to send
$queryString = "?" . http_build_query(array("phone" => $jsonString));
echo "Query string to send is: " . $queryString . PHP_EOL;
// PHP side: this is not a real HTTP GET request, but to pretend we have
// got some data in, we'll use the same query string, parse it, and store it
// in $params
$incoming = parse_url($queryString, PHP_URL_QUERY);
parse_str($incoming, $params);
// now print contents of "phone" parameter
echo "URL parameter phone contains " . $params["phone"] . PHP_EOL;
// JSON-decode the "phone" parameter
var_dump(json_decode($params["phone"], true));
This should print:
Query string to send is: ?phone=%7B+%22phone%22%3A+%5B+%22123%22%2C+%22456%22%2C+%22789%22%5D+%7D
URL parameter phone contains { "phone": [ "123", "456", "789"] }
array(1) {
'phone' =>
array(3) {
[0] =>
string(3) "123"
[1] =>
string(3) "456"
[2] =>
string(3) "789"
}
}
which shows the JSON decodes to a proper PHP array. An array of strings, to be precise, and not numbers as requested. Turning the strings into numbers in PHP will be easy to do, but maybe you could also make sure on the call site that you send numbers and not strings.
If your original code does not work, I guess the incoming data is either no properly encoded JSON or there is some magic escaping going on (magic quotes hell, should be turned off in today's PHP, but could be a reason for garbled script input).
To make sure your JSON data is not truncated and to also save you from potential URL-encoding issues, I also suggest sending the JSON via HTTP POST, not HTTP GET.

JSON Extracting Data Into Variable Using PHP

I'm using a YouTube data API request to grab the channel id, but i'm not too sure why it isn't working:
The returned JSON request i'm getting is:
{
"kind": "youtube#channelListResponse",
"etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/k5qSWj-xcF96jAN3p1uQH1amSRc\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#channel",
"etag": "\"PSjn-HSKiX6orvNhGZvglLI2lvk/e1xTbLf6JLhwwzeWbdMfWdPfcwg\"",
"id": "UC-lHJZR3Gqxm24_Vd_AJ5Yw"
}
]
}
To extract the JSON data i'm using the a few lines of code and a function in php:
$banner_data = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=brandingSettings&forUsername=pewdiepie&key=AIzaSyDTxvTLWXStUrhzgCDptVUG4dGBCpyL9MY');
$banner_data = json_decode($banner_data, true);
$YTid = $banner_data['items']['id'];
When i :
echo "YouTube Channel Id Of pewdiepie is " . $YTid . ".<br />";
I don't get the channel id? What's my problem?
Items is an array containing one or more objects. So it has to be:
$YTid = $banner_data['items'][0]->id;
This way you grab 'id' from the first item in the items-array.
BTW: learning to debug is crucial to learning to code. If you decode the json and then print the outcome you can see the structure of the array, which could have helped you to find the problem, like:
$banner_data = json_decode($banner_data, true);
var_dump($banner_data);
Try this instead:
$YTid = $banner_data['items'][0]['id'];

how do i get this json data from php server in android

how do i get this json data in android
this data is in localhost. I must fetch this data using URL and display in listview in android.Can any one help in coding plz
[
{
"id":"111114",
"name":"Prandar"
},
{
"id":"111115",
"name":"Catmilkend"
},
{
"id":"111110",
"name":"Allan"
},
{
"id":"111111",
"name":"Aircornal"
},
{
"id":"111112",
"name":"Allaxander"
},
{
"id":"111113",
"name":"AppleMacro"
}
]
This is a very common need, but involves several independent steps which could easily be their own StackOverflow question.
1) in a file named info.php you will create the JSON string to return to requests:
<?php
// this may come from a database
$info = array ('id' => '101',
'name'=> 'bill'
)
echo json_encode($info); // returns {"id":'101',"name": "bill"}
?>
2) Send a http GET request to myserver.com/info.php and capture the string response.
http://w3mentor.com/learn/java/android-development/android-http-services/example-of-http-get-request-using-httpclient-in-android/
3) Then parse the JSON into objects or dictionary array with a JSON framework.
http://www.jondev.net/articles/Android_JSON_Parser_Example
4) Use a ListView in Android to display it.
http://developer.android.com/resources/tutorials/views/hello-listview.html

Categories