I've got this PHP code
<?php
$json = file_get_contents('comments.json');
$decode = json_decode($json);
$name = $_POST['name'];
$email = $_POST['email'];
$comment = $_POST['comment'];
foreach($decode->comments as $key)
{
var_dump(array(
$key->name,
$key->email,
$key->comment
));
}
$decode->comments = array(array('name'=>$name, 'email'=>$email, 'comment'=>$comment));
$encode = json_encode($decode,JSON_FORCE_OBJECT);
file_put_contents('comments.json',$encode);
?>
It kind of works, it sets the current stuff in the JSON file to what its told to in this piece of PHP code. Instead of this, I want the PHP code to add on to the JSON that is already existing.
This is the JSON file.
{
"comments": {
"0": {
"name": "123",
"email": "123",
"comment": "123"
}
}
}
Pass a boolean true so you get an associative array instead of an object-based decode:
$json = file_get_contents('comments.json', true);
Change all of your OOP references to associative array style:
foreach($decode['comments'] as $key)
{
var_dump($key); // Declaring a whole new array isn't really needed here
}
Append to the decoded JSON array using the [] syntax:
$decode['comments'][] = array(
'name' => $name,
'email' => $email,
'comment' => $comment,
);
Re-encode and return the resulting JSON:
$encode = json_encode($decode, JSON_FORCE_OBJECT);
file_put_contents('comments.json',$encode);
Related
I am trying to sent response in that form
{"files":[{"webViewLink":""},{"webViewLink":""}]}
But I'm getting response like that
{"files":[{"webViewLink":"""}]}{"files":[{"webViewLink":"""}]}
Here is my PHP code:
<?php
$idtemp = extractfiles($fol_id, $email);
foreach ($idtemp['items'] as $val) {
$id = $val['id'];
$val = array(
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
);
$enc = json_encode($val);
$val = '{"files":['.$enc.']}';
echo($val);
Please help me to fix code i need response in that way
{"files":[{"webViewLink":""},{"webViewLink":""}]}
You should no do $val = '{"files":['.$enc.']}';
Use json_encode to make json, don't do it manual
Create an object with desired keys outside the loop
Push anything to the desired array
Convert to json
<?php
$idtemp = extractfiles($fol_id, $email);
$json = (object) [
"files" => []
];
foreach ($idtemp['items'] as $val) {
$json->files[] = (object) [
"webViewLink" => 'https://drive.google.com/file/d/'.$val['id'].'/view?usp=drivesdk"'
];
}
$json = json_encode($json);
echo($json);
If I use some dummy values to create an example, the output is:
{
"files": [
{
"webViewLink": "https://drive.google.com/file/d/1/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/2/view?usp=drivesdk\""
},
{
"webViewLink": "https://drive.google.com/file/d/3/view?usp=drivesdk\""
}
]
}
As you can test in this online demo
I'm processed some JSON data that is sent via HTTP POST to my PHP file. I then need to extract some elements and create a PHP array containing these, so I can then loop through this array and perform some actions.
Here's a sample of how the JSON data that is sent looks:
[
{
"fileName": "Invoices",
"event": "processed",
"serverName": "server1.acme.com",
"timestamp": 1574229999
},
{
"fileName": "Invoices",
"event": "processed",
"serverName": "server2.acme.com",
"timestamp": 1574228341
},
{
"fileName": "Payments",
"event": "processed",
"hostname": "server3.acme.com",
"timestamp": 1574766997
}
]
I'm then decoding this to parse out just the elements I need:
$payload = #file_get_contents('php://input');
$records= json_decode( $payload, FALSE );
$sessionsArray = array();
foreach($records as $record){
$hostname = $record->hostname;
$fileName = $record->fileName;
// need to add these to the $sessionsArray for each iteration of the loop
}
I would like to create a new array $sessionsArray and add the $hostname and $fileName variables to this for each iteration in the foreach loop. I then intend to do another foreach on the $sessionsArray and perform some actions using the $hostname and $fileName for each element of the array.
I'm stuck on how to add the variables within the first foreach loop to the $sessionsArray array so I can then subsequently loop through that array.
foreach($records as $record){
$sessionsArray[] = [
'hostname' => $record->hostname,
'fileName' => $record->fileName,
];
}
And then you can do:
foreach($sessionsArray as $entry){
$hostname = $entry['hostname'];
$fileName = $entry['fileName'];
}
=== OR ===
foreach($records as $record){
$sessionsArray[$record->hostname] = $record->fileName;
}
and then you can do:
foreach($sessionsArray as $hostname => $fileName){
// $hostname contains the hostname
// $filename contains filename
}
Just FYI, based on the JSON object you provided your code SHOULD be:
$hostname = $record->serverName;
$fileName = $record->fileName;
$sessionsArray = array();
foreach($records as $key => $record){
$sessionsArray[$key]['hostname'] = $record->hostname;
$sessionsArray[$key]['fileName'] = $record->fileName;
}
You need to get the last key of sessionsArray before every loop and pass that last key while adding to variable.
Here is example:
$sessionsArray = !empty($sessionsArray)?$sessionsArray:[];
$continueKey = (#array_pop(array_keys($sessionsArray)))?#array_pop(array_keys($sessionsArray))+1:0;
foreach($records as $record){
$sessionsArray[$continueKey]['hostname'] = $record->hostname;
$sessionsArray[$continueKey]['fileName'] = $record->fileName;
}
I have a .json file and I want to append an object to a vector in the file, but I got some errors.
$json = file_get_contents('materialsdb/'.$_POST["materialtype"].'.json');
$jsonarray = json_decode($json, true);
$myObj->short = $_POST["short"];
//here I got: Warning: Creating default object from empty value
$myObj->title = $_POST["title"];
$myObj->description = $_POST["description"];
$myObj->cover = "";
$myObj->VR = false;
$myObj->slow = false;
$td = '2D';
$myObj->$td = false;
$fd = '3D';
$myObj->$fd = false;
if($_POST["isprivate"]){
$myObj->license = "nonfree";
} else {
$myObj->license = "free";
}
$myObj->lang = "en";
$id = count($jsonarray['packages'])+1;
$myObj->id = $id;
$myObj->soon = false;
$myObj->date = $_POST["date"];
$myObj->creator = $_POST["creator"];
$myObj->creator_institution = $_POST["creator_institution"];
$myObj->keywords = $_POST["keywords"];
$myObj->data = $_POST["data"];
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
//here I got: Warning: array_push() expects parameter 1 to be array, string given
$jsondata = json_encode($jsonarray, true);
$myFile = 'materialsdb/'.$_POST["materialtype"].'.json';
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
} else
echo "error";
And when I try to save it then It is saved, but without the modifications, without the new object, but where I echo $myJSON there the object seems good.
Here is an example of my .json file:
{
"description": "some description",
"creators": [
{
"name": "cname",
"whoishe": "cv",
"avatar": "",
"id": 123
}
],
"lang": "en",
"materialname": "mat name",
"generalmaterialid": "mat_id",
"thismaterialid": "this_mat_id",
"packages": [
{
"short": "pack short desc",
"title": "pack title",
"description": "pack long desc",
"cover": "pack cover",
"VR": true,
"slow": true,
"2D": true,
"3D": true,
"license": "free",
"lang": "en",
"id": 1,
"soon": false
}
]
}
I have been inspired from here: https://www.w3schools.com/js/js_json_php.asp and here http://www.kodecrash.com/javascript/read-write-json-file-using-php/.
What have I done wrong here? How can I resolve it? What is the correct version in this case? Thanks for any help!
Firstly, you've got your arguments to array_push() back to front. The array you want to insert into has to be the first argument you give to the function.
Secondly, you're appending a JSON string ($myJSON) to the array, instead of your object data. This doesn't work because when you later come to encode the whole array as JSON, the bit that's already a JSON string is simply treated as a string, and ends up being double-encoded. You need to push the actual PHP object to the array. It will be encoded later when everything else is.
So
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
can become simply
array_push($jsonarray['packages'], $myObj);
P.S. You can also remove the warning about "Creating default object from empty value" by writing
$myObj = new \stdClass();
just before the line
$myObj->short = $_POST["short"];
so that you're adding your properties to an object which already exists.
I'm struggling on how to properly create a JSON file and append data to it, here's my PHP code:
<?php
$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];
//Load the file
$jsonStr = file_get_contents($jsonFile);
//Decode the JSON data into a PHP array.
$array = json_decode($jsonStr, true);
if ($array != null) {
$arrNew['ObjID']++;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
} else {
$arrNew = [];
$array['ObjID'] = 0;
$array['username'] = $username;
$array['email'] = $email;
array_push($array, $arrNew);
}
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);
// echo data
echo $jsonData;
?>
If I refresh the URL in my browser by calling my php file, I get this output if i go to example.com/_users.json
{
"0": [],
"1": {
"ObjID": 1,
"username": "bob",
"email": "b#doe.com"
},
"2": {
"ObjID": 1,
"username": "sarah",
"email": "b#doe.com"
},
"3": {
"ObjID": 1,
"username": "sarah",
"email": "b#doe.com"
},
"ObjID": 0,
"username": "bob",
"email": "b#doe.com"
}
So I'm able to generate a .json file, but what I need to do is a piece of code to do the following sequence:
Since the first time I run the script, the _users.json file doesn't exist, it needs to get generated
Create a JSON main object
Insert 1st object inside the main object
Append a 2nd object (still inside the main object)
And so on with 3rd, 4th, etc..
So I would need to get an output like this:
{ <-- Main Object starts
"1": { <-- 1st object inside the Main Object
"ObjID": 1,
"username": "bob",
"email": "b#doe.com"
},
"2": { <-- 2nd object
"ObjID": 1,
"username": "sarah",
"email": "s#doe.com"
}
} <-- Main Object closes
I can't really figure out what I'm doing wrong in my PHP code.
Logic in the else part should be inverted:
} else {
$array = [];
$arrNew['ObjID'] = 0;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
}
Try below code.
$jsonFile = "_users.json";
$username = $_GET["username"];
$email = $_GET["email"];
$objID = $_GET["objID"];
//Load the file
$jsonStr = file_get_contents($jsonFile);
//Decode the JSON data into a PHP array.
if($jsonStr=='') $array = array();
else $array = json_decode($jsonStr, true);
if (empty($array)) {
$arrNew = [];
$arrNew['ObjID']=0;
$arrNew['username'] = $username;
$arrNew['email'] = $email;
array_push($array, $arrNew);
} else {
$array['ObjID'] ++;
$array['username'] = $username;
$array['email'] = $email;
array_push($array, $arrNew);
}
// Encode the array back into a JSON string and save it.
$jsonData = json_encode($array);
file_put_contents($jsonFile, $jsonData);
// echo data
echo $jsonData;
?>
I make a modification in my json with this code:
$id = "hotel_name";
$value ="My Hotel";
$json = json_decode(file_get_contents('datas.json'));
$datas = $json->datas;
foreach ($datas as $category => $data) {
foreach ($data as $element) {
if($element->id==$id) {
$datas->$category->$element->$id = $value;
}
}
}
$newJson = json_encode($element);
file_put_contents('datas.json', $newJson);
But it do not put all the content in it.
How to solve it please ?
My json has the following:
{
"datas": {
"General": [
{
"field": "hotel_name",
"name": "My Hotel name"
}
]
}
}
You are accessing the $element variable, which contains only your inner most data
{
"field": "hotel_name",
"name": "My Hotel name"
}
If you want more of your data, you will have to reassign your outermost $datas variable and children with the newly updated $element variable. I'd recommend creating an empty variable to store the new data instead of altering the original copy.
You should be encoding datas, not just the last element, right?
// before
$newJson = json_encode($element);
// after
$newJson = json_encode($datas);
By the way, you might find it easier to work with the data if you convert it to an array rather than object.
$json = json_decode(file_get_contents('datas.json'), true);