PHP Put more than one object into json file - php

So I've been working on this PHP API thing for a while, and it would save JSON to a PHP file. The code works, but only allows 1 object. How do I add another object without removing the old JSON (Appending JSON)
<?php
//-- Parameters --\\
$id = $_GET['id'];
$language = $_GET['language'];
$filter = $_GET['filter'];
$commands = $_GET['commands'];
$name = $_GET['name'];
$members = $_GET['members'];
//-- Read and Parse JSON --\\
$string = file_get_contents("./Data/Guilds.json");
$json_a = json_decode($string, true);
if(isset($json_a[$id])) {
}
else {
//-- Initialize Array --\\
$obj[$id] = Array();
//-- Set Array Objects --\\
$obj[$id]["language"] = $language;
$obj[$id]["filter"] = $filter;
$obj[$id]["commands"] = $commands;
$obj[$id]["information"]["name"] = $name;
$obj[$id]["information"]["members"] = $members;
//-- Encode and Write --\\
$fp = fopen('./Data/Guilds.json', 'w+');
fwrite($fp, $json);
fclose($fp);
}

Related

How can I array_chunk mysqli results into chunks of 100 at a time

Is there a way I can Array_chunk mysqli results, I am looping messages from a table and later pass the values into a method "Sms" The method will create a List of Sms objects which I pass through a function SendBatchSMS. my API end points can only allow 100 call per request.
I have tried array chunking the list into "$sms" which seams to work well when I print_r($sms), but when echo the response, it returns only 48/249 responses regardless of the size specified in the array_chunk function. My question is, is there a better option to achieve this, something like array_chunking the mysqli results instead of the array list?
$query_sch = "SELECT * FROM ct_queue";
$sch_result = mysqli_query($mysqli, $query_sch);
$rows[] = mysqli_fetch_array($sch_result);
$count = mysqli_num_rows($sch_result);
foreach($sch_result as $value)
{
$phone = $value['phone'];
$sender = $value['sender'];
$message = $value['message'];
$user_id = $value['user_id'];
$link_id = NULL;
$correlator = 'correlator_string';
$endpoint = 'example.com';
$token = "token_string";
// $list = array();
$version = "v1"; //DONT change unless you are using a different version
$instance = new BonTech($token, $version);
$list[] = new Sms($sender, $phone, $message, $correlator, null, $endpoint);
}
$row_chunks = array_chunk($list, 100);
foreach ($row_chunks as $chunk){
$sms = array();
////////here we have 100 messages on each chunk
///////Loop through the messages in side the chunk
foreach ($chunk as $row) {
$sms[] = ($row);
}
// print_r($sms);
}
$response = call_user_func_array(array($instance, "sendBatchSMS"), $sms);
$response = json_encode($response, true);
$results = json_decode($response, true);
print_r($response);
You're using $sms after the foreach loop is done. So it will only contain the last chunk. You need to use it inside the loop.
There's also no need to use a loop to copy $chunk to $sms.
You're also skipping the first row of results because of your call to mysqli_fetch_array($sch_result) before the first foreach loop.
$instance doesn't seem to be dependent on $value, so it shouldn't be in the foreach loop.
$query_sch = "SELECT * FROM ct_queue";
$sch_result = mysqli_query($mysqli, $query_sch);
$list = array();
foreach($sch_result as $value)
{
$phone = $value['phone'];
$sender = $value['sender'];
$message = $value['message'];
$user_id = $value['user_id'];
$link_id = NULL;
$correlator = 'correlator_string';
$endpoint = 'example.com';
$list[] = new Sms($sender, $phone, $message, $correlator, null, $endpoint);
}
$token = "token_string";
$version = "v1"; //DONT change unless you are using a different version
$instance = new BonTech($token, $version);
$row_chunks = array_chunk($list, 100);
foreach ($row_chunks as $sms){
$response = call_user_func_array(array($instance, "sendBatchSMS"), $sms);
print_r($response);
}

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

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.

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;

how to put array data into text file using php

if i use the following code i got data in text file
{"title":"sankas","description":"sakars","code":"sanrs"}
{"title":"test","description":"test","code":"test"}
but my code is working on
{"title":"sankas","description":"sakars","code":"sanrs"}
so i could not add more rows.where i want to change to get correct results.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
$fd = fopen($file, "a"); // a for append, append text to file
fwrite($fd, $json);
fclose($fd);
use php's file_put_content() more information here http://php.net/manual/en/function.file-put-contents.php
Update :
assuming that the data is correctly being passed. here is what you can do.
$info = array();
$folder_name = $this->input->post('folder_name');
$info['title'] = $this->input->post('title');
$info['description'] = $this->input->post('description');
$info['code'] = $this->input->post('code');
$json = json_encode($info);
$file = "./videos/overlay.txt";
//using the FILE_APPEND flag to append the content.
file_put_contents ($file, $json, FILE_APPEND);
Update 2:
if you want to access the value back from the text file. overlay.txt here is what you can do
$content = file_get_contents($file);
if you want to fetch title, code, and description separately. and if the string is in json then you need to convert it into array first by using.
//this will convert the json data back to array
$data = json_decode($json);
and to access individual value you can do it like this if you have one row
echo $data['title'];
echo $data['code'];
echo $data['description'];
if you have multiple rows then you can use php foreach loop
foreach($data as $key => $value)
{
$key contains the key for example code, title and description
$value contains the value for the correspnding key
}
hope this helps you.
Update 3:
do it like this
$jsonObjects = file_get_contents('./videos/overlay.txt');
$jsonData = json_decode($jsonObjects);
foreach ($jsonData as $key => $value) {
echo $key . $value;
//$key contains the key (code, title, descriotion) and $value contains its corresponding value
}

Categories