Ashwin Reddy
Ashwin Reddy

Reputation: 31

PHP convert JSON object to string

I am making a quiz script. I want a "teacher" to be able to edit the questions. Originally, I tried to use mySQL but it was a bit difficult, so I decided to switch to a JSON file.

After doing some basic checks with PHP, I wrote this block of code

$json = array();
for ($x=1; $x < $count + 1; $x++) { 
    $q_and_a = array(
        "Question" => $_POST["q".$x],
        "Answer" => $_POST["a".$x]
        );
    array_push($json, $q_and_a);    
}
$encoded_array = json_encode($json);
// Delete JSON file, create new one and push encoded array into file
$json_file = 'questions.json';
unlink($json_file);
$handle = fopen($json_file, 'w') or die('Cannot open file:  '.$json_file);
fwrite($handle, $json_string) or die('Internal Sever Error');

After I got an internal server error, I realized that this is because the $json variable is an array; I need to convert it into a string and then insert it into the file. I first used serialize() but that just inserted some weird stuff into my file. How do I convert the json array into a string before moving it into the file?

Thanks In Advance

Upvotes: 1

Views: 1607

Answers (2)

hendr1x
hendr1x

Reputation: 1501

fwrite($handle, $encoded_array) or die('Internal Sever Error');

Upvotes: 0

Dharman
Dharman

Reputation: 33237

Try this piece of code. It doen't use JSON but it still saves data into a file which is split up using tab

<?php 
$count=10;//whatever you defined it to
$qa = "";
for ($x=1; $x < $count + 1; $x++) { 
    $qa .= $_POST["q".$x]."\t".$_POST["a".$x]."\n";   
}
$json_file = 'file.txt';
unlink($json_file);
file_put_contents($qa);
?>

<?php
//to retrieve q&a
$qas = file('file.txt',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$qas = explode("\t",$qas);
foreach($qas as $question => $answer)
{
    //your code 

}
?>

Upvotes: 1

Related Questions