How to save JSON Nested value using PHP as txt.file or Mysql database
Get the solution ↓↓↓I have a nested JSON object and i want to save the values into a txt file. This is the nested Json object
"objectJSON":{
"alt":"136.22",
"lat":"46.7484",
"lng":"33.0685"
}
I use the following PHP code to save the values into a txt.file
<?php
header("Content-type: application/json");
$json = file_get_contents("php://input");
$obj = json_decode($json);
$decoded = base64_decode(json_encode($obj->data));
$encoded = json_encode($obj->objectJSON);
$fp = @fopen("TMP.txt", "a"); //Open and write into TMP.txt
fwrite($fp, $encoded);
fwrite($fp,"\r\n");
fclose($fp);
?>
And here are the values into the TMP.txt file
"{\"alt\":136.22,\"lat\":46.7484,\"lng\":33.0685}"
And here is the problem:
What do I have to change/add to save only the "alt" value in the TMP.txt file?
HERE ARE MORE INFORMATION ABOUT MY PROJECT.
I receive the data via a lora node to a lora gateway which send them to my lora server. Here is a part from the lora node code that has been uploaded on it:
void GPSWrite()
{
/*Convert GPS data to format*/
datastring1 +=dtostrf(flat, 0, 6, gps_lat);
datastring2 +=dtostrf(flon, 0, 6, gps_lon);
//datastring3 +=dtostrf(falt, 0, 2, gps_alt);
if(flon!=1000.000000)
{
strcat(gps_lon,",");
strcat(gps_lon,gps_lat);
//strcat(gps_lon,",");
//strcat(gps_lon,gps_alt);
int i = 0;
for(i = 0; i < 2; i++)
{
//datasend.toFloat();
atof(gps_lon);
//Serial.println((char*)datasend);
Serial.println("Testing converted data:");
Serial.println(gps_lon);
// atof(gps_alt);
// Serial.print(gps_alt);
}
strcpy(datasend,gps_lon); //the format of datasend is longtitude,latitude,altitude
Serial.print("########### ");
Serial.print("NO.");
Serial.print(count);
Serial.println(" ###########");
Serial.println("The longtitude and latitude are:");
Serial.print("[");
Serial.print((char*)datasend);
Serial.print("]");
Serial.print("");
/*
for(int k = 0; k < 20;k++)
{
Serial.print("[");
Serial.print(datasend[k], HEX);
Serial.print("]");
}
Serial.println("");
Serial.println("");*/
count++;
}
int32_t lat = flat * 10000;
int32_t lng = flon * 10000;
datasend[0] = lng;
datasend[1] = lng >> 8;
datasend[2] = lng >> 16;
datasend[3] = lat;
datasend[4] = lat >> 8;
datasend[5] = lat >> 16;
smartdelay(1000);
}
static void smartdelay(unsigned long ms)
{
unsigned long start = millis();
do
{
while (ss.available())
{
gps.encode(ss.read());
}
} while (millis() - start < ms);
}
void loop() {
os_runloop_once();
}
The application server decodes the data with the following function:
function Decode(fPort, bytes) {
var decoded = {};
var hexString=bin2HexStr(bytes);
return rakSensorDataDecode(hexString);
}
// convert array of bytes to hex string.
// e.g: 0188053797109D5900DC140802017A0768580673256D0267011D040214AF0371FFFFFFDDFC2E
function bin2HexStr(bytesArr) {
var str = "";
for(var i=0; i<bytesArr.length; i++) {
var tmp = (bytesArr[i] & 0xff).toString(16);
if(tmp.length == 1) {
tmp = "0" + tmp;
}
str += tmp;
}
return str;
}
// convert string to short integer
function parseShort(str, base) {
var n = parseInt(str, base);
return (n << 16) >> 16;
}
// convert string to triple bytes integer
function parseTriple(str, base) {
var n = parseInt(str, base);
return (n << 8) >> 8;
}
// decode Hex sensor string data to object
function rakSensorDataDecode(hexStr) {
var str = hexStr;
var myObj = {};
while (str.length > 4) {
var flag = parseInt(str.substring(0, 4), 16);
{
myObj.lat = (bytes[3] | bytes[4]<<8 | bytes[5]<<16 | (bytes[5] & 0x80 ? 0xFF<<24 : 0)) / 10000;
myObj.lng = (bytes[0] | bytes[1]<<8 | bytes[2]<<16 | (bytes[2] & 0x80 ? 0xFF<<24 : 0)) / 10000;
myObj.alt = ((bytes[6] << 8) + bytes[7])/100;
str = str.substring(22);
}
}
return myObj;
}
so I get through my application server the following results: received data
Then I use the php script to save data on txt, file. As I have told you, the problem is that I can save all data but can't save for example only the altitude.
Answer
Solution:
The only thing you have to do is decode and then encode and write the proper one:
$json = file_get_contents("php://input");
$obj = json_decode($json);
file_put_contents("TMP.txt", json_encode($obj->objectJSON->alt));
If you want to append then:
file_put_contents("TMP.txt",
file_get_contents("TMP.txt") . json_encode($obj->objectJSON->alt));
But that won't be valid JSON in the file.
Answer
Solution:
You are using the encoded data, instead use decoded data if you want to access the 'alt' attribute, here is an example :
<?php
$obj = (object) [
"objectJSON" => [
'alt' => '136.22',
'lat' => '46.7484',
'lng' => '33.0685'
]
];
$encoded = json_encode($obj->objectJSON);
$decoded = json_decode($encoded);
$fp = @fopen("TMP.txt", "a"); //Open and write into TMP.txt
fwrite($fp, $decoded->alt);
fwrite($fp,"\r\n");
fclose($fp);
?>
Answer
Solution:
You just need to extract the value from theobject
:
$fp = @fopen("TMP.txt", "a"); //Open and write into TMP.txt
fwrite($fp, $decoded->alt);
// ^^^^^^^
fwrite($fp,"\r\n");
fclose($fp);
Answer
Solution:
Finally, I can save my data in a txt file and I can insert my data into a MySQL database at the same time. Thank you all for your help. Here is the PHP script
<?php
header("Content-type: application/json");
$json = file_get_contents("php://input");
$obj = json_decode($json);
$decoded = base64_decode(json_encode($obj->data));
$fp = @fopen("TMP.txt", "a"); //Open and write into TMP.txt
fwrite($fp,$decoded);
fwrite($fp,"\r\n");
fclose($fp);
$server = "#######";
$username = "#######";
$password = "#######";
$DB = "#######";
$conn = new mysqli($server, $username, $password, $DB);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$insert = "INSERT INTO gpssensor(longitude, latitude) VALUES ($decoded)";
$conn->query($insert);
$conn->close();
?>
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: a non-numeric value encountered
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.