I have this php code that give data from database and then convert to a json text file, my database name is gengroup_testwebapp and my json file is jsonparsetutorial.txt :
<?php
// open a connection to mysql
$conn = mysqli_connect("localhost","gengroup_ali","GenGroup$2015","gengroup_testwebapp")
or die("Error is : ".mysqli_error($conn));
//fetching data to php
$sql = "select * from country_info";
$result = mysqli_query($conn , $sql) or die("Error is : ". mysqli_error($conn));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
// convert php array to json String and \n
//write to json file
$fp = fopen('jsonparsetutorial.txt', 'worldpopulation');
fwrite($fp, json_encode($emparray));
fclose($fp); ?>
I wanna convert this code to json array file. how can I convert its data to a json file like this:
{ "worldpopulation":
[
{
"rank":1,"country":"China",
"population":"1,354,040,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/china.png"
},
{
"rank":2,"country":"India",
"population":"1,210,193,422",
"flag":"http://www.gengroup.ir/testwebapp/flag/india.png"
},
{
"rank":3,"country":"United States",
"population":"315,761,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/unitedstates.png"
},
{
"rank":4,"country":"Indonesia",
"population":"237,641,326",
"flag":"http://www.gengroup.ir/testwebapp/flag/indonesia.png"
},
{
"rank":5,"country":"Brazil",
"population":"193,946,886",
"flag":"http://www.gengroup.ir/testwebapp/flag/brazil.png"
},
{
"rank":6,"country":"Pakistan",
"population":"182,912,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/pakistan.png"
},
{
"rank":7,"country":"Nigeria",
"population":"170,901,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/nigeria.png"
},
{
"rank":8,"country":"Bangladesh",
"population":"152,518,015",
"flag":"http://www.gengroup.ir/testwebapp/flag/bangladesh.png"
},
{
"rank":9,"country":"Russia",
"population":"143,369,806",
"flag":"http://www.gengroup.ir/testwebapp/flag/russia.png"
},
{
"rank":10,"country":"Japan",
"population":"127,360,000",
"flag":"http://www.gengroup.ir/testwebapp/flag/japan.png"
}
] }
Simply do this.
$arr['worldpopulation']= $emparray[];
$fp = fopen('jsonparsetutorial.txt', "w");
fwrite($fp, json_encode($arr));
fclose($fp); ?>
Don't forget to mention mode of open like w for write.
Related
I have this data but I can't parse it in the way I want. this is what I get:
{
"navigations": {
"title": "Facebook",
"link": "https://facebook.com",
"behavior": "EXTERNAL"
}
}
And what I expect to see:
{
"navigations": [
{
"title": "Facebook",
"url": "https://facebook.com",
"behavior": "INAPP"
},
{
"title": "Youtube",
"url": "https//youtube.com",
"behavior": "INAPP"
}
]
}
I have more results in my database but not more than 12 result so, i want to fetch data in the format i expect. I tried to do it using fetch_array but no success.
This is my PHP code:
$query_update_navigations = $db->prepare("SELECT title, link, behavior FROM navigation_tabs WHERE secret_api_key=?");
$query_update_navigations->bind_param("s", $_SESSION['secret_api_key']);
$query_update_navigations->execute();
$rows = array();
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'] = $rows1;
}
$store_path = '../apis/navigation_tabs/';
$file_name = $_SESSION['secret_api_key'] . '.json';
$sign_constants = json_encode($rows);
file_put_contents($store_path . $file_name, $sign_constants);
I searched for an answer but nothing solved my issue :(
You need to push the row onto the array, not overwrite it each time.
$rows = array('navigations' => []);
$result = $query_update_navigations->get_result();
while($rows1 = $result->fetch_assoc()) {
$rows['navigations'][] = $rows1;
}
My client sent me this JSON so I can loop and save the data in Mysql. I just can not get it because it's different from what I work at;
Can someone give me some hint and what is the difference from one format to another.
Error presented is: Warning: Invalid argument supplied for foreach () in line 28
foreach ($ json_data ['service_devices'] as $ key => $ value) {
Formator EX I've ever worked with:
{
"ordem_de_servico": [
{
"oser_numero_os": 23940493,
"oser_address_name": NAME;
CUSTOMER JSON
ordem_de_servico:
{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
My last attempt
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "webservice";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Read JSON file
$json = file_get_contents('oss.json');
//Decode JSON
$json_data = json_decode($json,true);
foreach($json_data['ordens_de_servico'] as $key => $value){
$os = $value["oser_numero_os"];
$data_abertura = $value["oser_dt_abertura"];
foreach($json_data['ordens_de_servico'][$key]['faturas'] as $index => $row){
$valorParcelas = $row["total_fatura"];
$sql = "SELECT numero_os FROM os WHERE numero_os = '$os'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "PULAR FATURA"."<p>";
}else {
$sql = "INSERT INTO faturas (valorParcelas, numero_os) VALUES ('$valorParcelas', '$os')";
if ($conn->query($sql) === TRUE) {
echo "<strong>".$valorParcelas." - FATURA OK"."</strong>"."<p>";
} else {
echo "Error Fatura";
}
}
}
$sql = "SELECT numero_os FROM os WHERE numero_os = '$os'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "PULAR"."<p>";
}
else{
$sql = "INSERT INTO os (numero_os, data_abertura) VALUES ('$os', '$data_abertura')";
if ($conn->query($sql) === TRUE) {
echo "<strong>".$os." - GRAVADO"."</strong>"."<p>";
} else {
echo "Error";
}
}
}
$conn->close();
?>
Change the line:
foreach($json_data['ordens_de_servico'] as $key => $value){
To:
foreach($json_data as $key => $value){
Since the new data doesn't have the outer element ordens_de_servico
Or you could edit the JSON file and add that element (don't forget to add the closing braces at the end as well.
Edit the first two lines of the file:
ordem_de_servico:
{
To:
{
"ordem_de_servico": [
And change the end of the file:
}
To:
]
}
Your JSON is incorrect. The main problem is json data itself which is not valid for json_encode() to generate PHP array.
First Possible solution:Remove ordem_de_servico: from our customer json and that will gonna work.
For json_decode(); method the json data must be valid and valid data is
{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
Second possible solution:What you can do is remove ordem_de_servico: string from your customer json data or make your json provider provide valid json data as follows with ordem_de_servico:.
{
"ordem_de_servico":{
"oser_numero_os":23940493,
"oser_dt_abertura":"28/03/2018",
"servico":{
"serv_cod_servico":60,
"serv_descr_servico":"CORTE POR DEBITO"
},
"cliente":{
"clie_ident_cliente":638617,
"nome":"MARIA APARECIDA FERREIRA DO NASCIMENTO"
},
"unidade_consumidora":{
"unid_ident_uc":2436434,
"logr_nome_logr_expandido":"R JOSE GUIMARAES"
},
"faturas":[
{
"total_fatura":"88.44",
"ftcd_mes_ano_fatmto":"2017-04-01"
},
{
"total_fatura":"45.16",
"ftcd_mes_ano_fatmto":"2017-03-01"
}
]
}
}
Look at the valid JSON format for json_decode() and there is not different types of json data only one type i.e. json.
I want to enter some details that included in JSON arrays to database.
Given below is my source code.
here is my data json array from the txt file
{
"reader_name":"Biboy Pogi",
"mac_address":"00:16:25:10:7E:85",
"tag_reads":[
{
"antennaPort":1,
"epc":"2015031687850100010105B5",
"tid":"E280110520005A8B952F0886",
"isHeartBeat":false
}
]
}
{
"reader_name":"Biboy Pogi",
"mac_address":"00:16:25:10:7E:85",
"tag_reads":[
{
"antennaPort":1,
"epc":"2015031687850100010105B5",
"tid":"E280110520005A8B952F0886",
"isHeartBeat":false
}
]
}
Assuming that you source data come in one json per row. You can do the iteration insert with the below sample code:
$fn = 'debug.txt';
$raw = file_get_contents($fn);
$raw = explode("\r\n", $raw);
foreach($raw as $row){
//force it to array for single item
if (substr($row, 0, 1) != '[')
$row = '[' . $row . ']';
$data_arr= json_decode($row, true);
foreach ($data_arr as $data){
$reader_name = $data['reader_name'];
$mac_address = $data['mac_address'];
$antennaPort = $data['tag_reads'][0]['antennaPort'];
$epc = $data['tag_reads'][0]['epc'];
$tid = $data['tag_reads'][0]['tid'];
$sql = "INSERT INTO tags(reader_name, mac_address, antennaPort, epc, tid)
VALUES('$reader_name', '$mac_address', '$antennaPort', '$epc', '$tid')";
if(!mysqli_query($con, $sql))
{
die('Error : ' . mysqli_error($con));
}
}
}
your json seems to be the problem.
try this:
[
{
"reader_name": "Biboy Pogi",
"mac_address": "00:16:25:10:7E:85",
"tag_reads": [
{
"antennaPort": 1,
"epc": "2015031687850100010105B5",
"tid": "E280110520005A8B952F0886",
"isHeartBeat": false
}
]
},
{
"reader_name": "Biboy Pogi",
"mac_address": "00:16:25:10:7E:85",
"tag_reads": [
{
"antennaPort": 1,
"epc": "2015031687850100010105B5",
"tid": "E280110520005A8B952F0886",
"isHeartBeat": false
}
]
}
]
You'r JSON is wrong and two times the same. Maybe you'll need it that way, but this one of them
{
"reader_name": "Biboy Pogi",
"mac_address": "00:16:25:10:7E:85",
"tag_reads": [
{
"antennaPort": 1,
"epc": "2015031687850100010105B5",
"tid": "E280110520005A8B952F0886",
"isHeartBeat": false
}
]
}
And you can't reach $antennaPort = $data['antennaPort']; that way. You have to call it like this
$antennaPort = $data['tag_reads']['antennaPort'];
$epc= $data['tag_reads'][0]['epc'];
$tid= $data['tag_reads'][0]['tid'];
EDIT
Insert into you'r database like this
mysqli_query($con,$sql)
After that, you should check for errors
if(!mysqli_query($con, $sql))
die ('Error in query: ' . mysqli_error($con));
Or you go in one line
mysqli_query($con, $sql) or die(mysqli_error());
I am trying to build a JSON response from my server side, but it is not working as expected.
It is probably something simple but, I am not so good at PHP...
The basic expected response is a JSON with a single JsonArray and some other fields, for that, the relevant piece of code is shown here:
Sample of expected JSON response:
{
"pageNr": 2
"totalPages":28
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
Basic PHP code used to generate desired JSON (among sql query and other things):
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = ['pageNr' => $page];
$response = ['totalPages' => $totalPages];
$response = ['products' => $res2];
Response that this code is generating on Postman:
{
"products":[
{
"user_name":"testUser001",
"product_ID":"4756373abdhg"
},
{
"user_name":"testUser002",
"product_ID":"475ggdfghghg"
},
{
"user_name":"testUser003",
"product_ID":"47466gdgbdhg"
},
{
"user_name":"testUser004",
"product_ID":"4000nfaergeb"
},
{
"user_name":"testUser005",
"product_ID":"adfer73abdhg"
}
]
}
So, for some reason the JSON response is not accepting more fields pageNrand totalPages.
What is wrong here?.
Each assignment overwrites your array. You need to update it instead:
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response = [];
$response['pageNr'] = $page;
$response['totalPages'] = $totalPages;
$response['products'] = $res2;
Try;
$res = array();
$res2 = array();
while($r = mysqli_fetch_assoc($query2)) {
$res["user_name"] = $r["user_name"];
$res["product_ID"] = $r["prod_ID"];
array_push($res2,$res);
}
$response .= ['pageNr' => $page];
$response .= ['totalPages' => $totalPages];
$response .= ['products' => $res2];
A get in my PHP script JSON string that looks like this (array with any objects):
[
{
"source":"symbols/2/2.png",
"ypos":133,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":252,
"depth":5,
"height":159,
"xpos":581
},
{
"source":"symbols/2/2.png",
"ypos":175,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":258,
"depth":3,
"height":163,
"xpos":214
},
{
"color":"0",
"ypos":468.38,
"fontSize":28,
"xpos":156.95,
"rotation":0,
"type":"MyTextArea",
"width":268.05,
"depth":7,
"height":244.62,
"fontFamily":"Verdana Bold",
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28"
}
]
How i can save each JSON object in this array with a record in mySQL?
Try this:
<?php
$json = '[
{
"source":"symbols/2/2.png",
"ypos":133,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":252,
"depth":5,
"height":159,
"xpos":581
},
{
"source":"symbols/2/2.png",
"ypos":175,
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28",
"rotation":0,
"type":"MyImage",
"width":258,
"depth":3,
"height":163,
"xpos":214
},
{
"color":"0",
"ypos":468.38,
"fontSize":28,
"xpos":156.95,
"rotation":0,
"type":"MyTextArea",
"width":268.05,
"depth":7,
"height":244.62,
"fontFamily":"Verdana Bold",
"template":"8B82CA47-41D2-D624-D6A2-37177CD82F28"
}
]';
//create a DB connection
con = mysql_connect("localhost","username","password");
mysql_connect _db('your_database',$con);
$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {
//how to use json array to insert data in Database
mysql_query("INSERT INTO tablename (source, ypos, template) VALUES ($value->source, $value->ypos,$value->template)");
}
mysql_close($con);
}
Note: But it is recommended to use PHP Data Objects(PDO) to do database operations.
Check here
Use json_decode and then construct a insert statement using the values of the array