Jump to content

Server-Side Scripting/Internet Data/PHP

From Wikiversity

index.php

[edit | edit source]
<?php

// This program reads JSON data from Wikidata with countries
// and Celsius temperatures. It displays the data in Celsius
// and Fahrenheit sorted in decending order by temperature.
//
// References:
//  https://www.mathsisfun.com/temperature-conversion.html
//  https://en.wikibooks.org/wiki/PHP_Programming
//  https://www.codewall.co.uk/how-to-read-json-file-using-php-examples/
//  https://meta.wikimedia.org/wiki/User-Agent_policy
//  https://gist.github.com/vyspiansky/82f4b1ef6fcff160047d

$URL = "https://query.wikidata.org/sparql";
$QUERY = '
SELECT DISTINCT ?Country ?MaximumTemperature WHERE {
  ?countryItem wdt:P31 wd:Q6256;
    p:P6591 ?maximumTemperatureRecord.
  ?maximumTemperatureRecord psv:P6591 ?maximumTemperatureValue.
  ?maximumTemperatureValue wikibase:quantityAmount ?maximumTemperatureQuantity;
    wikibase:quantityUnit ?temperatureUnit.
  {
    ?countryItem rdfs:label ?Country.
    FILTER((LANG(?Country)) = "en")
  }
  {
    ?temperatureUnit wdt:P5061 ?unitSymbol.
    FILTER((LANG(?unitSymbol)) = "en")
    FILTER(CONTAINS(?unitSymbol, "C"))
  }
  BIND(CONCAT(STR(?maximumTemperatureQuantity), " ", ?unitSymbol) AS ?MaximumTemperature)
}
ORDER BY (?Country)
';

main();

function main() {
    switch($_SERVER["REQUEST_METHOD"]) {
        case "GET":
            echo "<h1>Temperature Conversion</h1>";
            echo "<h2>Wikidata</h2>";
            echo get_data();
            break;
        default:
            echo "Unexpected request method:" . $_SERVER["REQUEST_METHOD"];
            break;
    } 
}

function get_data() {
    try {
        $data = get_raw_data($GLOBALS["URL"], $GLOBALS["QUERY"]);
        $records = get_records($data);
        return $records;
    } catch (Exception $exception) {
        return $exception->getMessage();
    }
}

function get_raw_data($url, $query) {
    $url = $url . "?query=" . urlencode($query);
    $url = $url . "&format=json";

    $user_agent = "Required by Wikidata";
    $options  = array("http" => array("user_agent" => $user_agent));
    $context  = stream_context_create($options);

    $data = file_get_contents($url, false, $context);
    $data = json_decode($data, true);
    return $data;
}

function get_records($data) {
    $records = [];
    foreach ($data["results"]["bindings"] as $array) {
        $record = get_record($array);
        array_push($records, $record);
    }
    usort($records, "compare_elements");
    $result = format_table($records);
    return $result;
}

function get_record($array) {
    $country = $array["Country"]["value"];
    $celsius = $array["MaximumTemperature"]["value"];

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

    $celsius = floatval(substr($celsius, 0, $index));
    $fahrenheit = $celsius * 9 / 5 + 32;

    $record = [];
    $record["country"] = $country;
    $record["celsius"] = $celsius;
    $record["fahrenheit"] = $fahrenheit;
    return $record;
}

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

function format_table($records) {
    $result = "<table><tr><th>Country</th>";
    $result = $result . "<th>Celsius</th>";
    $result = $result . "<th>Fahrenheit</th></tr>";

    for ($index = 0; $index < count($records); $index++) {
        $record = $records[$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

[edit | edit source]

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