Interactive PHP Quiz Form

What is a JSON file?

In PHP, you can read JSON file like this:

Interactive PHP Quiz Form

The following example reads quiz questions from a JSON file and creates an interactive quiz form using PHP.

quiz.php
     
<!DOCTYPE html>
<html>
<head>
    <title>Simple PHP Quiz</title>
    <link href="quiz.css" type="text/css" rel="stylesheet">
</head>
<body>
    
<h2 style="text-align:center;">PHP Quiz</h2>

<?php
//Reads the contents of a JSON file (questions.json) and converts it into a PHP array 
$questions = json_decode(file_get_contents("questions.json"), true);
//The true means: "Make it an associative array" instead of an object.

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $score = 0;
    $total = count($questions);

    echo '<div class="result">';
    echo "<h3>Quiz Results:</h3>";

    foreach ($questions as $index => $q) {

        if (isset($_POST["question$index"])) {
            $userAnswer = $_POST["question$index"];
        } else {
            $userAnswer = '';
        }

        $correctAnswer = $q['answer'];
        $isCorrect = $userAnswer === $correctAnswer;

        echo "<p><strong>" . htmlspecialchars($q['question']) . "</strong><br>";
        echo "Your answer: <span class='" . ($isCorrect ? "correct" : "incorrect") . "'>" . htmlspecialchars($userAnswer) . "</span><br>";
        echo "Correct answer: <strong>" . htmlspecialchars($correctAnswer) . "</strong></p>";

        if ($isCorrect) {
            $score++;
        }
    }

    echo "<h3>Your Score: $score / $total</h3>";
    if ($score == $total) {
        echo "<p>🎉 Great job!</p>";
    } elseif ($score >= $total / 2) {
        echo "<p>👍 Not bad, but try again for a perfect score!</p>";
    } else {
        echo "<p>💡 Keep practicing!</p>";
    }

    echo '<p><a href="' . htmlspecialchars($_SERVER['PHP_SELF']) . '">Take the quiz again</a></p>';
    echo '</div>';

} else {
    echo '<form method="post" action="' . htmlspecialchars($_SERVER['PHP_SELF']) . '" id="quizForm">';
    foreach ($questions as $index => $q) {
        echo '<div class="question">';
        echo "<p><strong>" . htmlspecialchars($q["question"]) . "</strong></p>";
        foreach ($q["choices"] as $choice) {
            echo '<label><input type="radio" name="question' . $index . '" value="' . htmlspecialchars($choice) . '" required> ' . htmlspecialchars($choice) . '</label>';
        }
        echo '</div>';
    }
    echo '<input type="submit" value="Submit Quiz">';
    echo '</form>';
}
?>

</body>
</html>