$origin_id, "destId" => $destination_id, "numB" => 1, "numF" => 5, "format" => "json", "useTrain" => 1 ]; $url = $base_url . "?" . http_build_query($params); $context = stream_context_create([ "http" => ["header" => "Authorization: Key $api_key"] ]); $response = file_get_contents($url, false, $context); if ($response === false) { return []; } $data = json_decode($response, true); $trips = $data["TripList"]["Trip"] ?? []; $results = []; foreach (array_slice($trips, 0, $num_trains) as $trip) { $leg = $trip["Leg"] ?? []; $name = $leg["name"] ?? "Unknown"; $type = $leg["type"] ?? "Unknown"; $origin = $leg["Origin"] ?? []; $departure_time = $origin["time"] ?? "Unknown"; $departure_date = $origin["date"] ?? ""; $track = $origin["track"] ?? "Unknown"; $destination = $leg["Destination"] ?? []; $arrival_time = $destination["time"] ?? "Unknown"; $arrival_date = $destination["date"] ?? ""; // Set timezone to match the API/source data $timezone = new DateTimeZone("Europe/Copenhagen"); try { $dep_datetime = DateTime::createFromFormat("d.m.y H:i", "$departure_date $departure_time", $timezone); $arr_datetime = DateTime::createFromFormat("d.m.y H:i", "$arrival_date $arrival_time", $timezone); $now = new DateTime("now", $timezone); if ($dep_datetime && $arr_datetime) { // Time until departure in minutes $time_diff = $dep_datetime->getTimestamp() - $now->getTimestamp(); $time_to_departure = ($time_diff > 0) ? floor($time_diff / 60) : "0"; // Prevent negative values // Duration in minutes $duration = floor(($arr_datetime->getTimestamp() - $dep_datetime->getTimestamp()) / 60); } else { $time_to_departure = "Unknown"; $duration = "Unknown"; } } catch (Exception $e) { $time_to_departure = "Error"; $duration = "Error"; } $results[] = [ "departure" => $departure_time, "arrival" => $arrival_time, "duration" => $duration, "name" => $name, "type" => $type, "track" => $track, "time_to_departure" => $time_to_departure, "final_destination" => $final_destination[0] ]; } return $results; } $origin = $_GET["origin"] ?? "008600617"; // Default: Roskilde St. $destination = $_GET["destination"] ?? "008600626"; // Default: København H $trains = get_train_departures($origin, $destination, 5); ?> Train Departures
Train Departures
swap_horiz
Departs Time Departs In Duration Arrival Track
min. min.