Reputation: 720
I have an "obj" object and a "str" string. How do i set the $str property from "obj"? This is my try:
$jsonStr = '{"foo":"bar","number":1}';
$jsonObj = json_decode($jsonStr);
$property = $_GET["prop"];
$jsonObj->$property = "value";
file_put_contents("OUT",json_encode($jsonObj));
It always outputs "{}"!
Note: Please sorry for bad english, i'm not a native english speaker.
EDIT: I've tried to var_dump() every single variable in the code.
"foo"
object(stdClass)#1 (1) {["foo"]:"value", ["number"]:1}
so the error is in file_put_contents("OUT",json_encode($jsonObj));
...
EDIT 2: I've found the error! In the real code, i had written
$jsonStr = '{"foo":"bar","number":1}';
$jsonObj = json_decode($jsonStr);
$property = $_GET["prop"];
$jsonObj->$property = "value";
file_put_contents("OUT",json_encode( ---->$jsonStr<----- ERROR! ));
Thanks for helping!
Upvotes: 1
Views: 81
Reputation: 720
Simply do
file_put_contents("OUT",json_encode($jsonObj));
instead of
file_put_contents("OUT",json_encode($jsonStr));
The code actually works! It was an spelling error.
Upvotes: 1