I have a JSON file that contains the following:
{\"faqitem\": [{ \"id\": \"faq1\", \"question\": \"Question 1\"}]}
I am trying to do two things
So take the whole JSON aspect out of it. That is just serialization. Think about how to make the data structure look the way you want. Think about your data structure. To me, it seems that is maybe not the best structure for your purposes and that perhaps you need your id
available as a lookup key, so when you add an item to the data structure your either create a new value at that id key or overwrite the value at that key.
If your data were structured like:
{"faqitem":
{
"faq1": "Faq content",
"faq2": "Faq 2 content"
}
}
Then your code code be as simple as:
$faqpage = 'includes/faq.json';
$file = file_get_contents($faqpage);
$obj = json_decode($file);
$newdata['id'] = "faq2";
$newdata['question'] = "This is the second question";
$obj->faqitem->{$newdata['id']} = $newdata['question'];
echo json_encode($obj);
$fh = fopen($faqpage, 'w') or die ("can't open file");
//okay now let's open our file to prepare it to write
fwrite($fh, json_encode($obj));
fclose($fh);