0

I have the following JSON file stored in a server. I am using a php script to add another object to this JSON file.

testjson1.json:

{
"feed": 
[
{
"id": "1",
"name": "Ram",
"status": "Very good restaurant!! water tastes soo good :)"
}
]
}

The php that i use to add an object is as follows:

<?php
$data=array("2","new","not so good");
$inp = file_get_contents('testjson1.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('testjson1.json', $jsonData);
?>

But the php file shows an error which says:

Warning: array_push() expects parameter 1 to be array, object given in /home/u160481344/public_html/jsonfinder.php on line 5

and the json file collapses into a single line. How can i solve this?

3 Answers 3

2

As per the documentation, if you don't want object from json_decode

   json_decode($tempArray, true);

Add second boolean parameter. Try and let me know.

Sign up to request clarification or add additional context in comments.

Comments

1

Add second boolean parameter TRUE, returned objects will be converted into associative array.

Just replace this line

$tempArray = json_decode($inp);

With this

$tempArray = json_decode($inp,true);

Comments

1

PHP function json_decode() decodes a JSON string, it takes a JSON encoded string and convert it into PHP variable.

The script written below return a PHP variable in an object data type.

$inp = file_get_contents('testjson1.json');
$tempArray = json_decode($inp);

But PHP function array_push() accepts only array as input parameters. There is a second parameter (optional) boolean type you can pass into the json_decode() function like json_decode($json_string, TRUE) which will return decode PHP variable in an associative array. You have to update your code like this -

$inp = file_get_contents('testjson1.json');
$tempArray = json_decode($inp, TRUE);

For more reference see this link PHP function json_decode().

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.