Too much JSON info - php

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']);

Related

Append multikey Json array in php?

I am working on a simple API for a web server where you can set answers to querys with multiple querys tied to one answer.
Here is my code so far but I need a way to append queries (multikeys) to each question (value) and I'm not sure how to fit it together.
$question = urldecode($_GET["q"]);
$admin = urldecode($_GET["admin"]);
$answer = urldecode($_GET["answer"]);
$donext = urldecode($_GET["donext"]);
if ($admin == "password123") {
$file = fopen("program.json", "a+") or die ("file not found");
$json = file_get_contents('program.json');
$data = json_decode($json, true);
$keys = array($q1, $q2, $q3); // need to append this with $q each time.
$train = array_fill_keys($keys, '$a."+".$donext');
//$data[$tagid] = $tagvalue;
$newjson = json_encode($data);
file_put_contents('program.json', $newjson);
fclose($file);
} else {
$file = fopen("program.json", "a+") or die ("file not found");
$json = file_get_contents('program.json');
$data = json_decode($json, true);
$a = $data->$q;
$piece = explode('+', $a);
$reply = $piece[0];
$nextcontext = $piece[1];
fclose($file);
echo $reply;
echo $donext;
}
How to put multiple keys to the same value:
<?php
$questionkeys = array('hi','hey','yo');
$answervalue = "hello to you too";
$outputarray = array_fill_keys($questionkeys, $answervalue);
echo $outputarray;
?>

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);

appending content to json file using php script

I am trying to append content to json file using php script.
output of file1 is
[
{"id":"filters","name":"filter_supptype_cp_01"}
]
output of file2 is
[
{"id":"drives","name":"hddcntrlr"},
{"id":"drives","name":"diskdrivedes"}
]
after appending the output should come as :
[
{"id":"filters","name":"filter_supptype_cp_01"},
{"id":"drives","name":"hddcntrlr"},
{"id":"drives","name":"diskdrivedes"}
]
but output is coming as : -
[
{"id":"filters","name":"filter_supptype_cp_01"}]
[{"id":"drives","name":"hddcntrlr"},
{"id":"drives","name":"diskdrivedes"}
]
Code that I have tried is:
$file = file_get_contents('makejson.json');
$data = json_decode($file);
$info[] = array('id'=>$attribute1, 'name'=>$sub_attr_name);
$newb = array_values((array)$info);
file_put_contents('makejson.json',json_encode($newb),FILE_APPEND);
please help!!!!
Decode both files, append the array, encode again:
$existingData = json_decode(file_get_contents('file1.json'));
$newData = json_decode(file_get_contents('file2.json'));
$existingData = array_merge($existingData, $newData);
file_put_contents('file1.json', json_encode($existingData));
The array_push() function inserts one or more elements to the end of an array.
Your code :
$file = file_get_contents('makejson.json');
$tempArray = json_decode($file);
array_push($tempArray, $data); // $data is your new data
$jsonData = json_encode($tempArray);
file_put_contents('makejson.json', $jsonData);
i hope this code to help to yoo after 6 ear.
if (isset($_POST['data']) && $_POST['data']) {
$dbfile = file_get_contents('data.json');
$data = json_decode($dbfile);
unset($dbfile);
$yourdata = $_POST['data'];
$data[] = $yourdata;
file_put_contents('data.json', json_encode($data));
unset($data); }
You don't need to append array. You need to overwrite it.
Try like:
$file = file_get_contents('makejson.json');
$data = json_decode($file);
$data[] = array('id'=>$attribute1, 'name'=>$sub_attr_name);
file_put_contents('makejson.json',json_encode($data)); //Overwrite it
It will overwrite with new array.

How to create a JSON array using 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.

Fetch, Decode and Re-encode JSON

I am attempting to fetch JSON from Instagram according to a number of URL parameters, the JSON is then decoded and then the objects required are then encoded into my own JSON format. Whilst I know this sound a little ridiculous, it is what is required. My only issue here is that for some reason it does not encode each section of JSON, it will only work for one item. The code is as below.
<?php
function instagram($count=16){
$igtoken = $_GET['igtoken'];
$hashtag = $_GET['hashtag'];
$url = 'https://api.instagram.com/v1/tags/'.$hashtag.'/media/recent/?access_token='.$igtoken.'&count='.$count;
$jsonData = json_decode((file_get_contents($url)));
$jsonData = json_decode((file_get_contents($url)));
foreach ($jsonData->data as $key=>$value) {
$response = array();
$response["data"] = array();
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
$result = json_encode($response);
}
return $result;
}
echo instagram();
?>
It will work for each section of JSON if I do something like this instead:
$result .= '<li>
'.$value->caption->from->username.'<br/>
'.$value->caption->from->profile_picture.'<br/>
'.$value->caption->text.'<br/>
'.$value->images->standard_resolution->url.'<br/>
'.$value->caption->created_time.'<br/>
</li>';
I feel I have bodged up somewhere with the array, however i'm not entirely sure.
What if we move $response["data"] and $result varia out of foreach?
Have you tried this?
$response = array();
$response["data"] = array();
foreach ($jsonData->data as $key=>$value) {
$data = array();
$data["createdtime"] = $value->caption->created_time;
$data["username"] = $value->caption->from->username;
$data["profileimage"] = $value->caption->from->profile_picture;
$data["caption"] = $value->caption->text;
$data["postimage"] = $value->images->standard_resolution->url;
array_push($response["data"], $data);
}
$result = json_encode($response);
return $result;

Categories