Server-Side Scripting/Associative Arrays/PHP
index.php
edit<?php
// This program reads a user-selected text file of countries
// and Celsius temperatures. It displays the data in Celsius
// and Fahrenheit sorted in decending order by temperature.
//
// File format:
// Country,Temperature
// American Samoa,37.2° C
// Bulgaria,45.2° C
//
// References:
// https://www.mathsisfun.com/temperature-conversion.html
// https://en.wikibooks.org/wiki/PHP_Programming
// https://www.php.net/manual/en/features.file-upload.post-method.php
$FORM = '
<h1>Temperature Conversion</h1>
<p>Select a comma-separated file of countries and Celsius temperatures:</p>
<form method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file">
<input type="submit">
</form>
';
main();
function main() {
switch($_SERVER["REQUEST_METHOD"]) {
case "GET":
echo $GLOBALS["FORM"];
break;
case "POST":
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK &&
is_uploaded_file($_FILES["file"]["tmp_name"])) {
echo "<h1>Temperature Conversion</h1>";
echo "<h2>" . $_FILES["file"]["name"] . "</h2>";
echo process_file($_FILES["file"]["tmp_name"]);
}
break;
default:
echo "Unexpected request method:" . $_SERVER["REQUEST_METHOD"];
break;
}
}
function process_file($filename) {
$text = file_get_contents($filename);
$lines = explode("\n", trim($text));
if (strpos(strtolower($lines[0]), "country") >= 0) {
array_shift($lines); // remove heading line
}
$table = [];
foreach ($lines as $line) {
try {
$record = process_line($line);
array_push($table, $record);
} catch (Exception $exception) {
return $exception->getMessage();
}
}
usort($table, "compare_elements");
$result = format_table($table);
return $result;
}
function process_line($line) {
$record = [];
$array = explode(",", $line);
if (count($array) != 2) {
throw new Exception("Invalid file format");
}
$record["country"] = $array[0];
$celsius = $array[1];
$index = strpos($celsius, "° C");
if ($index === FALSE) {
throw new Exception("Invalid file format");
}
$celsius = floatval(substr($celsius, 0, $index));
$record["celsius"] = $celsius;
$fahrenheit = $celsius * 9 / 5 + 32;
$record["fahrenheit"] = $fahrenheit;
return $record;
}
function compare_elements($a, $b) {
return $b["celsius"] - $a["celsius"];
}
function format_table($table) {
$result = "<table><tr><th>Country</th>";
$result = $result . "<th>Celsius</th>";
$result = $result . "<th>Fahrenheit</th></tr>";
for ($index = 0; $index < count($table); $index++) {
$record = $table[$index];
$result = $result . "<tr><td>" . $record["country"] . "</td>";
$result = $result . "<td>" . number_format($record["celsius"], 1) . "</td>";
$result = $result . "<td>" . number_format($record["fahrenheit"], 1) . "</td></tr>";
}
$result = $result . "</table>";
return $result;
}
?>
Try It
editCopy and paste the code above into the following free online development environment or use your own PHP compiler / interpreter / IDE.