2

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?

4
  • 2
    $tempArray = json_decode($fileTmp,true); array_push($tempArray, $newArray); try it and tell Commented Feb 25, 2017 at 14:01
  • Does the error happen also with the provided json file or only when starting with an empty one? Commented Feb 25, 2017 at 14:05
  • 2
    @Anant oh yes, thank you! didnt seen that... aghidini problem solved but it was with the provided json Commented Feb 25, 2017 at 14:06
  • @PatrickDully glad to help you.:):) Commented Feb 25, 2017 at 14:16

3 Answers 3

2

Add a second parameter to json_decode() and set it to true:-

$tempArray = json_decode($fileTmp,true); 
array_push($tempArray, $newArray);
Sign up to request clarification or add additional context in comments.

Comments

1

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();
}
...

4 Comments

Actually his json what he shown is valid, but this code is also useful to prevent from errors. so +1.
@Anant I agree that his input json is valid but I suspected that he was receiving the errors only at the beginning, that is when the input json was empty (or does not exist). I thought that json_decode should produce a valid array also with false as the second parameter, it should simply produce an array of objects, but the OP error is about the first parameter (i.e. the array).
when you will try to push an array into an array of objects you will get this error too (i think)
@Anant Actually it works (albeit the final array contains objects and the newly added array): codepad.org/ITdcXai5 it even produces a valid output json: codepad.org/V5STYCCB
-1

I complied code, it works. Check permissions for data.json file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.