NS API Class
Hi, 9 jaar geleden heb ik hier een class geplaatst om data via de NS API op te halen. Inmiddels is deze class gedateerd en werkt deze niet meer, vandaar dat ik hier een nieuwe versie plaats. Wat kan je met de class? - Reisadvies opvragen op basis van: van, naar (en via) station X - Lijst van stations ophalen - Lijst ophalen van arriveerde treinen op een station - Lijst ophalen van treinen die vertrekken vanaf een station - Lijst van storingen ophalen - Lijst van storingen ophalen voor een station Hoe gebruik je de class? Om de NS API te gebruiken heb je een API key nodig, deze kan je opvragen via het NS API portaal: https://apiportal.ns.nl/ Deze key geef je mee bij het oproepen van de class, hierna ben je klaar om de class te gebruiken. Bijgevoegd vind je example.php, waarin een voorbeeld staat hoe je de getTrips() functie kan gebruiken om reisadvies weer te geven. Voorbeeld: https://2g.be/NS/
<?php
/**
* Author gerhard.dev
* 13-02-2020
* Version 1.0
*/
class NSAPI
{
private $apiKey;
private $baseUrl = 'https://gateway.apiportal.ns.nl/';
private $stations = [];
/**
* constructor
* Set NS API key, get your API key here: https://apiportal.ns.nl
*
* @param required string $strApiKey
*/
public function __construct($strApiKey)
{
$this->apiKey = $strApiKey;
}
/**
* loadStations
* Retrieve and store all stations, so we only have to query them once
*/
private function loadStations()
{
if(empty($this->stations))
{
$aStations = $this->request('public-reisinformatie/api/v2/stations')->payload;
if($aStations && !empty($aStations))
{
foreach($aStations as $oStation)
{
$this->stations[strtolower($oStation->code)] = $oStation;
}
}
}
if(empty($this->stations))
throw new Exception('Failed to load stations');
}
/**
* getStation
* Retrieve station info
*
* @param required string $strSearch -> search by station name, (UIC, EVA, Station) code
*
* @return object station info
*/
public function getStation($strSearch)
{
$strSearch = strtolower($strSearch);
$this->loadStations();
if(isset($this->stations[$strSearch]))
return $this->stations[$strSearch];
else
{
foreach($this->stations as $oStation)
{
if(
$oStation->UICCode == $strSearch ||
$oStation->EVACode == $strSearch ||
strtolower($oStation->code) == $strSearch ||
strtolower($oStation->namen->lang) == $strSearch ||
strtolower($oStation->namen->kort) == $strSearch ||
strtolower($oStation->namen->middel) == $strSearch
)
return $oStation;
}
}
throw new Exception('Invalid station: '. $strStation);
}
/**
* getStations
* Retrieve list of stations
*
* @return array list of stations
*/
public function getStations()
{
$this->loadStations();
return $this->stations;
}
/**
* getArrivals
* Retrieve list of arrivals for specific station
*
* @param string $strStation -> station name or code
* @param (optional) string $strDateTime -> return arrivals starting from this given dateTime
* @param (optional) int $iMaxJourneys -> Max number of arrivals to return
* @param (optional) string $strLang -> Language to use for translatable messages
*
* @return array list of arrivals
*/
public function getArrivals($strStation, $strDateTime = '', $iMaxJourneys = 0, $strLang = '')
{
$aParameters = [];
if(!empty($strStation))
$aParameters['station'] = $this->getStation($strStation)->code;
if(!empty($strDateTime))
$aParameters['dateTime'] = date('c', strtotime($strDateTime));
if(!empty($strLang))
$aParameters['lang'] = $strLang;
if(!empty($iMaxJourneys) && (int) $iMaxJourneys > 0)
$aParameters['maxJourneys'] = (int) $iMaxJourneys;
return $this->request('public-reisinformatie/api/v2/arrivals', $aParameters)->payload->arrivals;
}
/**
* getDepartures
* Retrieve list of departures for specific station
*
* @param string $strStation -> station name or code
* @param (optional) string $strDateTime -> return departures starting from this given dateTime
* @param (optional) int $iMaxJourneys -> Max number of departures to return
* @param (optional) string $strLang -> Language to use for translatable messages
*
* @return array list of departures
*/
public function getDepartures($strStation, $strDateTime = '', $iMaxJourneys = 0, $strLang = '')
{
$aParameters = [];
if(!empty($strStation))
$aParameters['station'] = $this->getStation($strStation)->code;
if(!empty($strDateTime))
$aParameters['dateTime'] = date('c', strtotime($strDateTime));
if(!empty($strLang))
$aParameters['lang'] = $strLang;
if(!empty($iMaxJourneys) && (int) $iMaxJourneys > 0)
$aParameters['maxJourneys'] = (int) $iMaxJourneys;
return $this->request('public-reisinformatie/api/v2/departures', $aParameters)->payload->departures;
}
/**
* getDisruption
* Retrieve specific disruption info
*
* @param string $strDisruption -> Dispruption ID
*
* @return object disruption info
*/
public function getDisruption($strDisruptionId)
{
return $this->request('public-reisinformatie/api/v2/disruptions/'. $strDisruptionId)->payload;
}
/**
* getDisruptions
* Retrieve list of disruptions
*
* @param (optional) boolean $bActual -> If true, only the disruptions from the last 2 hours will be returned
* @param (optional) string $strType -> WERKZAAMHEID or STORING, both will be returned by default
* @param (optional) string $strLang -> Language to use for translatable messages
*
* @return array list of disruptions
*/
public function getDisruptions($bActual = true, $strType = '', $strLang = '')
{
if(!empty($strType))
$aParameters['type'] = strtolower($strType);
$aParameters['actual'] = !!$bActual;
if(!empty($strLang))
$aParameters['lang'] = $strLang;
return $this->request('public-reisinformatie/api/v2/disruptions', $aParameters)->payload;
}
/**
* getStationDisruptions
* Retrieve list of disruptions for specific station
*
* @param string $strStation -> station name or code
*
* @return array list of disruptions
*/
public function getStationDisruptions($strStation)
{
return $this->request('public-reisinformatie/api/v2/disruptions/station/'. $this->getStation($strStation)->code)->payload;
}
/**
* getTrips
* Retrieve list of available trips based on the travel data provided
*
* @param string $strFrom -> station name or code to travel from
* @param string $strTo -> station name or code to travel to
* @param (optional) string $strVia -> station name or code to travel through
* @param (optional) string $strDateTime -> return trips starting from this given dateTime
* @param (optional) boolean $bDepature -> If false $strDateTime is the time of arrival
* @param (optional) string $strClass -> Class of travel, first or second
* @param (optional) string $strLang -> Language to use for translatable messages
*
* @return array list of trips
*/
public function getTrips($strFrom, $strTo, $strVia = '', $strDateTime = '', $bDepature = true, $strClass = '', $strLang = '')
{
$aParameters = [];
if(!empty($strFrom))
$aParameters['fromStation'] = $this->getStation($strFrom)->code;
if(!empty($strTo))
$aParameters['toStation'] = $this->getStation($strTo)->code;
if(!empty($strVia))
$aParameters['viaStation'] = $this->getStation($strVia)->code;
if(!empty($strDateTime))
{
$aParameters['dateTime'] = date('c', strtotime($strDateTime));
$aParameters['departure'] = !!$bDepature;
}
if(!empty($strClass))
{
$strClass = strtoupper($strClass);
if($strClass == 'FIRST' || $strClass == 'SECOND')
$strClass .= '_CLASS';
$aParameters['travelClass'] = $strClass;
}
if(!empty($strLang))
$aParameters['lang'] = $strLang;
return $this->request('public-reisinformatie/api/v3/trips', $aParameters)->trips;
}
/**
* getRequestInfo
* Retrieve parameters from a request
*
* @param string $strCtx -> ctxRecon
*
* @return object request info
*/
public function getRequestInfo($strCtx)
{
$aRequest = [];
$aCtx = explode('|', $strCtx);
if(!empty($aCtx))
{
foreach($aCtx as $strCtxPart)
{
$aCtxPart = explode('=', $strCtxPart);
if(count($aCtxPart) == 2)
$aRequest[$aCtxPart[0]] = strpos($aCtxPart[0], 'Station') !== false ? $this->getStation($aCtxPart[1]) : $aCtxPart[1];
}
}
return (object) $aRequest;
}
/**
* request
* Fires request and handles the response if they contain errors
*
* @param string $strEndpoint -> endpoint to request
* @param (optional) array $aParameters -> array of url parameters to send with the request
*/
public function request($strEndpoint, $aParameters = [])
{
$strUrl = $this->baseUrl . $strEndpoint;
if(!empty($aParameters))
$strUrl .= '?' . http_build_query($aParameters);
$ch = curl_init($strUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Ocp-Apim-Subscription-Key:'. $this->apiKey]);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
$strDefaultError = 'Something went wrong..';
if(isset($response->statusCode) && $response->statusCode != 200)
{
throw new Exception(isset($response->message) ? $response->message : $strDefaultError);
}
elseif(isset($response->code) && $response->code != 200)
{
$aErrors = [];
if(isset($response->errors) && !empty($response->errors))
{
foreach($response->errors as $oError)
{
$aErrors[] = $oError->message;
}
}
throw new Exception(empty($aErrors) ? $strDefaultError : implode(', ', $aErrors));
}
return $response;
}
}
?>
<?php
require 'ns.class.php';
try
{
$oNS = new NSAPI('-- api key --');
$aTrips = $oNS->getTrips('Groningen', 'Amsterdam centraal', 'Utrecht centraal', date('d-m-Y H:i:s'));
if(!empty($aTrips))
{
foreach($aTrips as $oTrip)
{
if(isset($oTrip->legs) && !empty($oTrip->legs))
{
$oStartLeg = $oTrip->legs[0];
$oEndLeg = $oTrip->legs[count($oTrip->legs)-1];
echo '<h4>'. $oStartLeg->origin->name .' - '. $oEndLeg->destination->name .'</h4>';
echo 'Vertrek: '. date('d-m-Y H:i', strtotime($oStartLeg->origin->actualDateTime ?? $oStartLeg->origin->plannedDateTime)) .'<br/>';
echo 'Aankomst: '. date('d-m-Y H:i', strtotime($oEndLeg->destination->actualDateTime ?? $oEndLeg->destination->plannedDateTime)) .'<br/>';
echo '<hr><ul>';
foreach($oTrip->legs as $oLeg)
{
$iDuration = (strtotime($oLeg->destination->actualDateTime ?? $oLeg->destination->plannedDateTime) - strtotime($oLeg->origin->actualDateTime ?? $oLeg->origin->plannedDateTime)) / 60;
echo '<li>'.
date('H:i', strtotime($oLeg->origin->actualDateTime ?? $oLeg->origin->plannedDateTime)) .' - '.
date('H:i', strtotime($oLeg->destination->actualDateTime ?? $oLeg->destination->plannedDateTime)) .' '.
$oLeg->origin->name .' - '. $oLeg->destination->name .' ('. $iDuration .' minuten)
</li>';
}
echo '</ul>';
}
echo '<hr>';
}
}
}
catch(Exception $e)
{
echo 'Error: '. $e->getMessage();
}
?>
Reacties
0