<?php
// File Encoding ส่วนของแฟ้ม Data เป็นแบบ ANSI ส่วน Script เป็นแบบ UTF-8 โดยใช้ฟังก์ชัน iconv() ในการเปลี่ยนรูปแบบ
if(!isset($_REQUEST["file"])) $file = 'test10math01'; else $file = htmlspecialchars($_REQUEST["file"]);
$header = '<!DOCTYPE html><html lang="th"><head><title>Exercise : '. $file .'</title><meta charset="utf-8" />
<style>input[type="radio"] { -ms-transform: scale(2); -webkit-transform: scale(2); transform: scale(2);margin-left:20px;margin-right:20px; }</style>
</head><body style="font-size:24px;font-weight:bold;background-color:#ddffff;">
<div style="width:600px;border:1px solid gray;margin-left:auto;margin-right:auto;display:block;background-color:white;">
<form method="post" action="' . $_SERVER['PHP_SELF'] . '">';
$footer = '<input type=hidden name=file value="'. $file .'"></form></div></body></html>';
$quiz_file = $file .'.txt';
function read_quiz_data($filename) {
$quiz_data = [];
$handle = fopen($filename, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// ถ้าข้อมูลเป็น UTF-8 ก็ไม่ต้องใช้ iconv กับ $line
$line = iconv('TIS-620','UTF-8//ignore',$line); // แปลงข้อมูลจาก ANSI เป็น UTF-8
$data = explode("\t", trim($line));
$quiz_data[] = $data;
}
fclose($handle);
}
return $quiz_data;
}
function generate_quiz_html($quiz_data) {
global $header, $footer;
$html = $header;
foreach ($quiz_data as $index => $question_data) {
$html .= '<p>' . ($index + 1) . '. ' . $question_data[1] . '</p>';
for ($i = 3; $i < count($question_data); $i++) {
if($question_data[2] == $i - 2) $check = 1; else $check = 0;
$html .= '<input type="radio" name="q' . $index . '" value="' . $check . '">' . $question_data[$i] . '<br>';
}
$html .= "\r\n";
}
$html .= '<input type="submit" value="Submit" style="width:300px;height:80px;font-size:30px;margin-left:auto;margin-right:auto;display:block;">';
$html .= $footer;
return $html;
}
function process_quiz_responses($quiz_data, $user_answers) {
global $file;
$correct_answers = 0;
for ($i = 0; $i < count($quiz_data); $i++) {
if ($user_answers['q' . $i] == 1) {
$correct_answers++;
echo "<script>alert('". 'question : ' . ($i + 1) ." : [ / ] Correct Answer!');</script>";
} else {
echo "<script>alert('". 'question : ' . ($i + 1) ." : [ X ] Wrong Answer!');</script>";
}
}
echo "<div style='margin-left:auto;margin-right:auto;display:block;font-size:30px;background-color:#ffffdd;border:1px solid gray;width:400px;'>
ท่านได้คะแนน $correct_answers จาก " . count($quiz_data) . " ข้อ<br/><a href='?file=". $file . "'>Back</a></div>";
}
$quiz_data = read_quiz_data($quiz_file);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
process_quiz_responses($quiz_data, $_POST);
} else {
echo generate_quiz_html($quiz_data);
}
?>