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.
Related
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());
<?php
$username = "root";
$password = "pw";
$host = "localhost";
$database="dbname";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "
SELECT `name`, `useTime`, `e_usage` FROM `electric_usage`
";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
I use upper php source to load mysql to JSON
the result of php page is
[{"name":"LED STAND","useTime":"2015-09-10 14:17:33","e_usage":"0.0599970581514709"},
{"name":"LED STAND","useTime":"2015-09-10 14:20:33","e_usage":"1.10919825898689"},
{"name":"LED STAND","useTime":"2015-09-10 14:23:33","e_usage":"1.9208018439918"}]
how to change this format to like this(for nvd3 line graph)?
function cumulativeTestData() {
return [
{
key: "LED STAND",
values: [ [ 2015-09-10 14:17:33 , 2.974623048543] ,
[ 2015-09-10 14:20:33 , 1.7740300785979]]
}
}
or theres easy way to make NVD3 line graph from mySql DB?
edit :
d3.json("./mysqljson/dbread.php", function(data) {
var dataLoad = d3.nest()
.key(function(d){return d.name})
.rollup(function(u){
return u.map(function(x){return [x.useTime,x.e_usage]})})
.entries(data);
nv.addGraph(function() {
var chart = nv.models.multiBarChart()
.x(function(d) {return d[0]})
.y(function(d) {return d[1]})
.margin({top: 50, bottom: 30, left: 40, right: 10});
chart.xAxis
.tickFormat(function(d) {
return d3.time.format('%x')(new Date(d))
});
d3.select('#mainExample')
.datum(dataLoad)
.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
});
working code to use d3.json and d3.nest function
You can achieve that by using d3's d3.nest() method as follows:
Assuming your data structure as you received it using d3.json is data, then if you do:
x=d3.nest()
.key(function(d){return d.name})
.rollup(function(u){
return u.map(function(x){return [x.useTime,x.e_usage]})})
.entries(data);
Then the result would be:
{
key = "LED STAND"
values = [
["2015-09-10 14:17:33", "0.0599970581514709"],
["2015-09-10 14:20:33", "1.10919825898689"],
["2015-09-10 14:23:33", "1.9208018439918"]
]
}
I hope this helps.
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.
My PHP script works fine, but for some element, i get null values whereas in the table the text is well here :
[
{
"etat":"online",
"nb_visiteurs":"0",
"id":"1",
"date_debut":"19\/05\/2014",
"prix":"40",
"description":null,
"id_author":"1",
"titre":null
},
{
"etat":"online",
"nb_visiteurs":"0",
"id":"2",
"date_debut":"21\/05\/2014",
"prix":"30",
"description":null,
"id_author":"1",
"titre":null
},
{
"etat":"offline",
"nb_visiteurs":"0",
"id":"3",
"date_debut":"22\/05\/2014",
"prix":"23",
"description":"TOP NOIR STYLE ASIATIQUE EN BON ETAT T 3\r\n\r\nFAIRE PROPOSITION",
"id_author":"1",
"titre":"Top noir style asiatique en bon etat t3"
},
{
"etat":"online",
"nb_visiteurs":"0",
"id":"4",
"date_debut":"22\/05\/2014",
"prix":"45",
"description":null,
"id_author":"1",
"titre":"Lit+sommier+matelas+ table de chevet+commode"
}
]
Here is the content of my annonces table :
And here is the structure of the table :
<?php
$PARAM_hote='aaaaaa';
$PARAM_port='3306';
$PARAM_nom_bd='bbbbbbbbb';
$PARAM_utilisateur='ccccccccc';
$PARAM_mot_passe='dddddddddd';
// Create connexion to BDD
$connexion = new PDO('mysql:host='.$PARAM_hote.';port='.$PARAM_port.';dbname='.$PARAM_nom_bd, $PARAM_utilisateur, $PARAM_mot_passe);
try {
// Getting username / password
$username = $_POST['username'];
$password = $_POST['password'];
// Prepare SQL request to check if the user is in BDD
$result1=$connexion->prepare("select * from tbl_user where username = '".$username."' AND password = '".$password. "'");
$result1->execute();
// Getting all results in an array
$arrAllUser = $result1->fetchAll(PDO::FETCH_ASSOC);
// If the size of array is equal to 0, there is no user in BDD
if (sizeof($arrAllUser) == 0) {
echo "fail";
}
// In this case, a user has been found, create a JSON object with the user information
else {
// Getting id of the user
$id_user = $arrAllUser[0]['id'];
// Prepare a second SQL request to get all annonces posted by the user
$result2=$connexion->prepare(" select * from annonces where id_author = '".$id_user."' ");
$result2->execute();
// Getting all annonces posted by the user in an array
$arrAllAnnonces = $result2->fetchAll(PDO::FETCH_ASSOC);
// Set in key user the USER structure
$array['user'] = $arrAllUser[0];
// Set in key annonces all annonces from the user
$array['annonces'] = $arrAllAnnonces;
// JSON encore the array
$json_result = json_encode($array);
echo $json_result;
}
} catch(Exception $e) {
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
?>
It's happening because french letters, the function fails to parse them.
try to use flag JSON_UNESCAPED_UNICODE
json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE)
you can play with the flags
try this
$output = array();
foreach ($array as $row)
{
$output[]=array_map("utf8_encode", $row);
}
$json_result = json_encode($output);
echo $json_result;
agree with volkinc answer,if you have a new php version you can use
json_unescaped_unicode instead of json_encode
and if your php version 5.3 and older unescaped wont work , just add this function at the bottom of the script and use it instead of json_encode
function my_json_encode($in) {
$_escape = function ($str) {
return addcslashes($str, "\v\t\n\r\f\"\\/");
};
$out = "";
if (is_object($in)) {
$class_vars = get_object_vars(($in));
$arr = array();
foreach ($class_vars as $key => $val) {
$arr[$key] = "\"{$_escape($key)}\":\"{$val}\"";
}
$val = implode(',', $arr);
$out .= "{{$val}}";
}elseif (is_array($in)) {
$obj = false;
$arr = array();
foreach($in AS $key => $val) {
if(!is_numeric($key)) {
$obj = true;
}
$arr[$key] = my_json_encode($val);
}
if($obj) {
foreach($arr AS $key => $val) {
$arr[$key] = "\"{$_escape($key)}\":{$val}";
}
$val = implode(',', $arr);
$out .= "{{$val}}";
}else {
$val = implode(',', $arr);
$out .= "[{$val}]";
}
}elseif (is_bool($in)) {
$out .= $in ? 'true' : 'false';
}elseif (is_null($in)) {
$out .= 'null';
}elseif (is_string($in)) {
$out .= "\"{$_escape($in)}\"";
}else {
$out .= $in;
}
return "{$out}";
}
and use my_json_encode instead of json_encode and dont forget this line :
header('content-type:text/html;charset=utf-8');
thanks to the person who made this function i forgot from where i got it.
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