I want to adding array's to an existing .json file with with a HTML form.
this is my PHP:
$myFile = "data.json";
$newArray = array(
'name'=> $_POST['name'],
'date'=> $_POST['date']
);
$fileTmp = file_get_contents($myFile);
$tempArray = json_decode($fileTmp);
array_push($tempArray, $newArray);
$jsonData = json_encode($tempArray);
file_put_contents($myFile, $jsonData);
this is my JSON:
[
{
"name": "name 1",
"date": "01.02.2017"
},
{
"name": "name 2",
"date": "05.02.2017"
},
{
"name": "name 3",
"date": "05.03.2017"
}
]
The problem is i got the warning
"array_push() expects parameter 1 to be array, null given in..."
and in the JSON there's is only null. What is my problem with my code?
Add a second parameter to json_decode() and set it to true:-
$tempArray = json_decode($fileTmp,true);
array_push($tempArray, $newArray);
Apart from using the associative version of json_decode as already stated in the other answer, I think that the problem is your input json file.
You should check for valid content and create your default array if the json is empty:
$fileTmp = file_get_contents($myFile);
$tempArray = json_decode($fileTmp, true);
if (!$tempArray) {
$tempArray = array();
}
...
I complied code, it works. Check permissions for data.json file.
Related
This is my json.json file content
{
"Title": "Hello World",
"Inputs": [
{
"Id": "1",
"Title": "One"
},
{
"Id": "15",
"Title": "Fifteen"
}
]
}
I am trying to modify it as the follows -
$text = file_get_contents("json.json");
$json = json_decode($text,true);
foreach($json["Inputs"] as $input){
if($input["Id"]== "15"){
$input["Title"] = "This is from me.";
}
}
$new = json_encode($json);
file_put_contents('json.json', $new);
But the file is not being updated.
Any idea?
Your JSON in the example is improperly formatted, but the issue you are having is that you do not set the title in the original array. You change the copy that is passed to the foreach loop.
Change your foreach loop to this and your changes should be shown:
foreach($json["Inputs"] as $key => $input){
if($input["Id"]== "15"){
$json["Inputs"][$key]["Title"] = "This is from me.";
}
}
The foreach loop takes the value by reference, so changing the $json['Inputs'] will change the original value, whereas changing $input modifies the copy that is passed to the loop, and does not change the original json data. There are ways to pass by reference to the foreach loop, but this seems like a simpler solution.
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 try to read IME field in PHP from following JSON FORMAT:
{"komentarji": [ {"RC_KOMENTARJI": [ {
"K_ID": 101,
"STATUS": "A",
"IME": "boris",
"E_MAIL": "test#example.com",
"KOMENTAR": "testni vnos",
"IP": "10.0.0.6",
"DATUM_ZAPISA": "2016-12-03T23:23:47Z",
"DATUM_UREJANJA": "2016-12-03T23:24:01Z"
},
{
"K_ID": 1,
"STATUS": "A",
"IME": "Peter",
"KOMENTAR": "Zelo profesionalno ste opravili svoje delo.",
"IP": "10.0.0.8",
"DATUM_ZAPISA": "2011-05-04T00:00:00Z"
}
] } ] }
How can I reach that field via foreach in PHP? Thank you.
Let you decode the json to object named $result.
If you want to read first IME then try this
$result->komentarji[0]->RC_KOMENTARJI[0]->IME
If you want to read all IME then you have to apply loop throw komentarji and RC_KOMENTARJI
Decode it by using json_decode().
$object = json_decode($json);
// result in object
$array = json_decode($json, true);
// result in array
You can try this:
$array = json_decode($json, true);
foreach ($array['komentarji'] as $key => $value) {
foreach ($value['RC_KOMENTARJI'] as $k => $val) {
echo $val['IME'] . "<br/>";
}
}
This will print:
boris
Peter
Hope it helps!!!
I have this function in php
<?php function showTable(){
$url = "http://10.0.0.1/lib/api/desk/branch/";
$params = array ("action" => "list","company_key" => "1");
$result=requestURL($url,$params);
$json_a=json_decode(strip_tags($result),true);
?>
This is the json I got from the code above. I need to check the key "status". If it has a value "no", it should display an alert that status is not ok. Thanks!
{
"init": [
{
"status": "ok",
"record_count": 9,
"code": "",
"message": "",
"page_count": null,
"current_page": 0
}
]
}
Easy.
Suppose you hold the JSON in $json.
$jsonDecoded = json_decode($json, true);
if($jsonDecoded['init'][0]['status'] != 'ok') {
print "status is not ok :(";
}
Let say that json is in $json variable
$json = json_decode($json,true);
$status = $json['init'][0]['status'];
if($status=='ok'){
# do something here
}else{
# display not ok here
}
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);