I would like to push new object inside a JSON file with PHP but I don't find any solution on internet due to the format.
Here is my Json file.
{
"html": {
"snippet1": {
"id":"snippet1",
"title":"A title"
},
"snippet2": {
"id":"snippet2",
"title":"Another title"
}
}
}
And here is the php file
$json = file_get_contents('./content.json');
$data = json_decode($json);
$id = "snippet3";
$title= "My title";
I expect to push those new data inside the JSON.
The result should be:
{
"html": {
"snippet1": {
"id":"snippet1",
"title":"A title"
},
"snippet2": {
"id":"snippet2",
"title":"Another title"
},
"snippet3": {
"id":"snippet3",
"title":"My title"
}
}
}
Thank you
$json = file_get_contents('./content.json');
$data = json_decode($json, true); //added true to make it an array
$id = "snippet3";
$title = "My title";
$data['html'][$id]['id'] = $id; //add the id to the array
$data['html'][$id]['title'] = $title; //add the title to the array
$newData = json_encode($data, true); //turn the array back into json
$writeJson = file_put_contents("content.json", $newData); //write the json array to json file
Related
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;
?>
When a new User is created, I save the username and password (no hashed) in a json file as well as in the DB, so every time I'm appending new users to the json file:
{
"user3": "demo"
} {
"user4": "demo"
} {
"user4": "demo"
} {
"user5": "demo"
}
the code:
$data = array($request->input('username') => $request->input('password'));
$datos = json_encode($data);
File::append(storage_path('archivos/datos.json'), $data);
of course the format above isn't valid json, how could i get this
[{
"user3": "demo"
}, {
"user4": "demo"
}, {
"user4": "demo"
}, {
"user5": "demo"
}, {
"user5": "demo"
}, {
"user5": "demo"
}, {
"user7": "demo"
}, {
"user8": "demo"
}]
and read it using foreach like this:
$result = File::get(storage_path('archivos/datos.json'));
$result = json_decode($result);
foreach($result as $key=>$item){
echo $key .''. $item;
}
First get the string from file then you can do a str_replace all "} {" with "} , {" a json also have [ at the start and ] at the end so we add them too:
$json = "[".str_replace('} {', '},{', $fileContent)."]";
Here we have a json string in $json variable so we can convert it to array by this:
$users = json_decode($json);
the fastest way would be to append some data:
fopen('myfile.json', 'a');
but you want to store an array, so you have to read the content of the file, update it and save it.
$users = json_decode(file_get_content(storage_path('archivos/datos.json')));
$users[] = $newUser;
file_put_contents(storage_path('archivos/datos.json'), json_encode($users, JSON_PRETTY_PRINT);
you can also make a one-liner (ugly, but works):
file_put_contents(storage_path('archivos/datos.json'), json_encode(json_decode(file_get_content(storage_path('archivos/datos.json')))[] = $newUser, JSON_PRETTY_PRINT);
I have a URL that returns a JSON object like this:
[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]
URL : http://www.myapifilms.com/imdb/top
I want to get all of the urlPoster value and set in a array's element, and convert array to JSON so echo it.
How can I do it through PHP?
You can do something like that :
<?php
$json_url = "http://www.myapifilms.com/imdb/top";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
$json = file_get_contents('http://www.myapifilms.com/imdb/top');
$array = json_decode($json);
$urlPoster=array();
foreach ($array as $value) {
$urlPoster[]=$value->urlPoster;
}
print_r($urlPoster);
You can simply decode the json and then pick whatever you need:
<?php
$input = '[
{
"idIMDB": "tt0111161",
"ranking": 1,
"rating": "9.2",
"title": "The Shawshank Redemption",
"urlPoster": "http:\/\/ia.media-imdb.com\/images\/M\/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg",
"year": "1994"
}
]';
$content = json_decode($input);
$urlPoster = $content[0]->urlPoster;
echo $urlPoster;
The output obviously is the URL stored in that property:
http://ia.media-imdb.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE#._V1_UX34_CR0,0,34,50_AL_.jpg
BTW: "The Shawshank Redemption" is one of the best films ever made...
This how you do the same thing with array_map function.
<?php
#function to process the input
function process_input($data)
{
return $data->urlPoster;
}
#input url
$url = 'http://www.myapifilms.com/imdb/top';
#get the data
$json = file_get_contents($url);
#convert to php array
$php_array = json_decode($json);
#process the data and get output
$output = array_map("process_input", $php_array);
#convert the output to json array and print it
echo json_encode($output);
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);