Jump to content

Server-Side Scripting/Arrays/PHP

From Wikiversity

index.php

[edit | edit source]
<?php

// This program reads a user-selected text file of countries
// and Celsius temperatures. It displays the data in Celsius
// and Fahrenheit sorted in descending 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 {
            $array = process_line($line);
            array_push($table, $array);
        } catch (Exception $exception) {
            return $exception->getMessage();
        }
    }

    usort($table, "compare_elements");
    $result = format_table($table);
    return $result;
}

function process_line($line) {
    $array = explode(",", $line);
    if (count($array) != 2) {
        throw new Exception("Invalid file format");
    }

    $celsius = $array[1];
    $index = strpos($celsius, "° C");
    if ($index === FALSE) {
        throw new Exception("Invalid file format");
    }

    $celsius = floatval(substr($celsius, 0, $index));
    $array[1] = $celsius;
    $fahrenheit = $celsius * 9 / 5 + 32;
    array_push($array, $fahrenheit);
    return $array;
}

function compare_elements($a, $b) {
    return $b[1] - $a[1];
}

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++) {
        $row = $table[$index];
        $result = $result . "<tr><td>" . $row[0] . "</td>";
        $result = $result . "<td>" . number_format($row[1], 1) . "</td>";
        $result = $result . "<td>" . number_format($row[2], 1) . "</td></tr>";
    }

    $result = $result . "</table>";
    return $result;
}

?>

Try It

[edit | edit source]

Copy and paste the code above into the following free online development environment or use your own PHP compiler / interpreter / IDE.