How to create a JSON array using PHP - php

My JSON data looks like this:
[
{
"email":"test#test.com",
"firstName":"test",
"lastName":"test",
"value":"test#test.com",
"tokens":"test#test.com"
},
{
...
}
]
and php data to create json file looks like this:
<?php
session_start();
include('connection.php');
$userId = $_SESSION['sess_user_id'];
$act = $_POST['action'];
$sth = mysql_query("SELECT email, firstName, lastName, email AS value, email AS tokens FROM User");
$rows = array();
while($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
$fp = fopen('./test.json', 'w');
fwrite($fp, json_encode($rows));
fclose($fp);
?>
When a user is added to the database, it runs this php code:
$file = './test.json';
$data = json_decode(file_get_contents($file), true);
$newdata = array('email'=>$email, 'firstName' => $firstName, 'lastName'=>$lastName, 'value'=>$email, 'tokens'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
I want the my JSON file to look like this:
[
{
"email":"test#test.com",
"firstName":"test",
"lastName":"test",
"value":"test#test.com",
"tokens":[
"test#test.com"
]
}
]
I tried to figure this out, but I couldn't. Please help?

php handles arrays different than javascript (which differentiates between objects and arrays).
$newdata = array(
'email'=>$email,
'firstName' => $firstName,
'lastName'=>$lastName,
'value'=>$email,
'tokens'=>array($email)
);
should do it.

Related

Encode table data to specific json format

Hi iam currently working on json based project.But iam having problem in encoding my data from my table like the below format.....I have seen a lot of json formats.....If any one can help me providing
php code snippet to encode exactly to such format.....
I need exactly such output where "data" is the array name
{
"data":[
{
"Id":1,
"Name":"Haben",
"Surname":"Dave",
"Age":22
},
{
"Id":12,
"Name":"Tomas",
"Surname":"Haleka",
"Age":32
},
{
"Id":123,
"Name":"Henok",
"Surname":"Dave",
"Age":28
},
{
"Id":1,
"Name":"Nafta",
"Surname":"Dave",
"Age":22
}
]
}
This will iterate through all selected rows and will encode them as Array. If you want to receive column names as they're in the table use below code.
$sql_query = "........";
$result = $db_connection->query($sql_query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode(array('data'=> $rows));
If you don't want to receive same column names as in database you can change how you want to receive them. You'll have to edit your while loop to do so.
while($r = mysqli_fetch_assoc($result)) {
$id = $r['user_id'];
$name = $r['user_name'];
$age = $r['user_age'];
$surname = $r['user_surname'];
$rows[] = array('Id' => $id, 'Name' => $name, 'Age' => $age, 'Surname' => $surname);
}

Create JSON file and display

I want to create a JSON file based in MySQL data but for some reasons my code is not working at all(I dont have any errors)
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$data = array();
foreach ($results as $row) {
$data[] = $row;
}
$json_string = json_encode($data);
$file = 'servers.json';
file_put_contents($file, $json_string);
What I want:
{
"ID": [
"IPOFTHESERVERFROMDATABASE",
PORTFROMDATABASE,
"NAMEFROMDATABASE"
],
..
}
What I'm getting:
[["ID","NAME","IP","PORT","RCON"]]
You are not putting anything into the $data array.
Change the code as below to load the rows into the $data array before json_encode()ing it
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$data = array();
foreach ($results as $row) {
$data[] = $row;
}
$json_string = json_encode($data);
$file = 'servers.json';
file_put_contents($file, $json_string);
Or as Ray says below, as you have used a fetchAll you could probably do without the foreach loop and do
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$json_string = json_encode($results);
$file = 'servers.json';
file_put_contents($file, $json_string);
EDIT: The output you wanted?
You say you want
{
"ID": [
"IP",
PORT,
"NAME"
],
"ID": [
"IP",
PORT,
"NAME"
]
}
which of course is not possible as you have 2 keys/properties with the same name i.e. "ID"
$results= $panel->query('SELECT * FROM servers ORDER BY id ASC;')->fetch_all();
$data = array();
foreach ($results as $row) {
$data[$row[0]] = [$row[2],$row[3],$row[1]];
}
$json_string = json_encode($data);
$file = 'servers.json';
file_put_contents($file, $json_string);

Invalid Array from json_decode()

I have a PHP file that grabs a .txt file and decodes the JSON to push the user's e-mail and name entry to my campaign monitor database. The JSON is wonky because new entries are added with a ][ as seen in this example:
[{"email":"drake.scott#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxxbyn\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/qbxbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"drake","custom_3_last":"scott","custom_4":"4146583264","fullname":"drake scott","id":"vvvbyn"}]
[{"email":"john.roberts#test.com","createdate":"2016-03-23 10:44:52","from_email":null,"from_liked_pageid":null,"source":"direct","bonus_entry_url":"\/xxx\/h1lvw5","entry_url":"https:\/\/admin.woobox.com\/manage\/offers\/entries\/20160314-1\/tu%2BcJmnsgyUxE7HM9BCqnRjnza27dGIdr%2BHymHrFmFoprsRgkhZradPrTJ5s18p6ewxYeOOKLpObd%2FWGAS%2BDRw%3D%3D","shareurl":"http:\/\/woobox.com\/vvvbyn\/h1lvw5","picked":"0","actionbutton":"","custom_3_first":"john","custom_3_last":"adams","custom_4":"4146585018","fullname":"john adams","id":"vvvbyn"}]
The problem I am having right now is uploading the entries to my database. I have managed to strip the ][ and doing a var_dump($content); shows a valid JSON string. However, doing var_dump($user) gives me 0 array(0) { }.
The entries will not upload to my database because there is essentially nothing in my array. Can anyone give me some insight on how to proceed?
<?php
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$content = str_replace('}][{', '},{', $content);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}
if($result->was_successful()) {
echo "Subscribed with code ".$result->http_status_code;
}
else {
echo "failed";
var_dump($result->response);
var_dump($user);
}
?>
There are multiple JSON objects concatenated in the file. The easiest way to make the JSON valid is to create an array:
$content = str_replace('][', ',', $content);
$users = json_decode($content, true);
Then you have a multi-dimensional array with multiple users that you will need to decide what you want from it:
print_r($users);
foreach($users as $user) {
echo $user['email'] . "\n";
}

Too much JSON info

I am using the following to convert data from mysql to JSON:
$sql = "select img_name from user_gallery_images where user_id=$_SESSION[user_id]";
$response = array();
$posts = array();
$result = $mysqli->query($sql);
while($row = $result->fetch_array()){
$file=$row['img_name'];
$fileDir = "gallery/$file.jpg";
$posts[] = array('thumb'=> $fileDir, 'image'=> $fileDir);
}
$response['posts'] = $posts;
$fp = fopen('/home/public_html/users/'.$settings[username].'/gallery/gallery.json', 'w');
$jsonData = stripslashes(json_encode($response));
fwrite($fp, $jsonData);
fclose($fp);
Which works well and creates e.g.
{"posts":
[
{"thumb":"gallery/tess1367386438.jpg","image":"gallery/tess1367386438.jpg"},
{"thumb":"gallery/tess1367386538.jpg","image":"gallery/tess1367386538.jpg"}
]
}
But, the JQuery plug in i'm using it with won't read it with the outer "posts" container
QUESTION:
How can I strip the outer "posts" container in the JSON to produce only:
[
{"thumb":"gallery/tess1367386438.jpg","image":"gallery/tess1367386438.jpg"},
{"thumb":"gallery/tess1367386538.jpg","image":"gallery/tess1367386538.jpg"}
]
Try
$jsonData = json_encode($response['posts']);

Pulling data from MySQL into json array

I'm trying to pull data from my database using json in php. I have a few elements I need to specific then to post them on a page.
I want to "fetch" the data from mysql and return it to a json_encode. How can I do this using the SELECT method. Some had used PDO methods and other have used mysql_assoc, which confuses me.
For instance,
I have rows of: 'id' , 'title' , 'start', 'backgroundColor'...etc. along with a default value for all of them. ($array[] = "someValue = default")
I want it to export like so:
array(
'id' => 1,
'title' => "someTitle",
'start' => "2012-04-16",
'backgroundColor' => "blue",
'someValue' = > "default",
...
), ....
));
If anyone could help me with this with the best detail, I'd be awesome!
If you wanted to do this with PDO then here is an example:
<?php
$dbh = new PDO("mysql:host=localhost;dbname=DBNAME", $username, $password);
$sql = "SELECT `id`, `title`, `time`, `start`, `backgroundColor`
FROM my_table";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//To output as-is json data result
//header('Content-type: application/json');
//echo json_encode($result);
//Or if you need to edit/manipulate the result before output
$return = [];
foreach ($result as $row) {
$return[] = [
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start'].' '.$row['time'],
'backgroundColor' => $row['backgroundColor']
];
}
$dbh = null;
header('Content-type: application/json');
echo json_encode($return);
?>
You don't "fetch to a json array".
You fetch your database results into a PHP array, then convert that php array, AFTER THE FETCHING IS COMPLETED, to a json string.
e.g.
$data = array();
while ($row = mysql_fetch_assoc($results)) {
$data[] = $row;
}
echo json_encode($data);
You can get the result from mysql,then format it to json
$array = array();
while($row = mysqli_fetch_array($result))
{
array_push($array,$row);
}
$json_array = json_encode($array);
Please check for SELECT methods here
In general it would look like this
$data = array(); // result variable
$i=0
$query = "SELECT id,title,start,backgroundColor FROM my_table"; // query with SELECT
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){ // iterate over results
$data['item'][$i]['id'] = $row['id']; // rest similarly
...
...
$i++;
}
header('Content-type: application/json'); // display result JSON format
echo json_encode(array(
'success' => true,
'data' => $data // this is your data variable
));

Categories