<?php

class PhpNsTrains {

/* API Base URL setting
* Note: currently HTTP, couldn't get the HTTPS to work so far
*/
private static $base_url = "http://webservices.ns.nl/";

private $authUser;
private $authPassword;

/* Constructor, takes API username and password obtainable from http://www.ns.nl/api */
function __construct($username, $password) {
Als ik deze veranderd doet hij het niet >>>>> $this->authUser = $username;
Als ik deze veranderd doet hij het niet >>>>> $this->authPassword = $password;
}

/*
* Return a list of stations, optionally an associative array with the
* given key from the return values (name, code, lat or long). Second parameter
* specifies whether or not to only include Dutch train stations
* NOTE: In most normal use cases, cache this result
*/
function getStations($key = null, $nlOnly = false) {
$xmlTree = $this->getUrl('ns-api-stations');

if (!in_array($key, array('name', 'code', 'lat', 'long')))
$key = null;

$output = array();
foreach($xmlTree as $xmlStation) {
$station = (array) $xmlStation;
if ($nlOnly && $station['country'] == 'NL') { // Check if dutch
if ($key) {
$output[$station[$key]] = $station;
} else {
$output[] = $station;
}
}
}
return $output;
}

/*
* Get a list of current service disruptions. Options are:
* - 'station': filtered for given station
* - 'actual': show current disruptions? (boolean)
* - 'unplanned': show planned engineering works? (boolean)
*
* TODO: Handle 'bericht' field and test unplanned disruptions and
* add a helper function here
*/
function getDisruptions($options = array()) {
$xmlTree = $this->getUrl('ns-api-storingen', $options);

$disruptions = array();
foreach($xmlTree->Gepland->Storing as $xmlNotice){
$notice = (array) $xmlNotice;
$disruptions[] = array('id' => $notice['id'], 'applicable' => $notice['Traject'], 'period' => $notice['Periode'],
'alternative' => $notice['Advies'], 'reason' => $notice['Reden'], 'delay' => $notice['Vertraging'], 'type' => 'planned');
}
foreach($xmlTree->Ongepland->Storing as $xmlNotice){
$notice = (array) $xmlNotice;
$disruptions[] = array('id' => $notice['id'], 'applicable' => $notice['Traject'], 'period' => $notice['Periode'],
'alternative' => $notice['Advies'], 'reason' => $notice['Reden'], 'delay' => $notice['Vertraging'], 'type' => 'unplanned');
}

return $disruptions;
}

/*
* Get a live list of departures for a given station, optionally with an name of key to use for the index
* Returns a list of departing trains if successfull, an string with error message, or false
*/
function getDepartures($station, $key = null) {
$xmlTree = $this->getUrl('ns-api-avt', array('station' => $station));

$output = array();
// Check if we actually found a list of trains or we got an error
if ($xmlTree->getName() != 'ActueleVertrekTijden') {
// Return the error, otherwise false
if ($xmlTree->getName() == 'error') {
return $xmlTree->message;
}
return false;
} else {
// Loop over each train entry
foreach($xmlTree as $xmlTrain) {
// Cast as an array to get access to most keys
$train = (array) $xmlTrain;
$add = array('departure' => strtotime($train['VertrekTijd']), 'service' => $train['RitNummer'],
'destination' => $train['EindBestemming'], 'type' => $train['TreinSoort'],
'carrier' => $train['Vervoerder'],
'platform' => $train['VertrekSpoor'], 'via' => $train['RouteTekst'] ? $train['RouteTekst'] : "");

// Decode any (optional) delay to a integer minute value
if (isset($train['VertrekVertraging'])) {
if (preg_match('/^PT(\d{0,3}?)M$/', $train['VertrekVertraging'], $matches)) {
$add['delay'] = $matches[1];
}
}

// Check if the platform was changed
$changed = false;
if($xmlTrain->VertrekSpoor->attributes()) {
$attr = (array) $xmlTrain->VertrekSpoor->attributes();
if (isset($attr['@attributes']['wijziging']) && $attr['@attributes']['wijziging'] == "true")
$changed = true;
}
$add['platform_changed'] = $changed;

// Add the various comments, also check if train is cancelled
$cancelled = false;
foreach($xmlTrain->Opmerkingen as $comment) {
$text = trim((string) $comment->Opmerking);
if ($text == "Rijdt vandaag niet") {
$cancelled = true;
}
$add['comments'][] = $text;
}
$add['cancelled'] = $cancelled;

// Add the train to our output list
$output[] = $add;
}
}
return $output;
}

/*
* List the available travel options given a origin and destination.
* Several options can also be set:
* - 'previousAdvices': number of ravel options to list in the past (max 5)
* - 'nextAdvices': number of ravel options to list in the future (max 5)
* - 'dateTime': arrival or departure time
* - 'departure': is the above parameter arrival or departure (boolean)
* - 'hslAllowed': also use highspeed trains? (boolean) - default: true
* - 'yearCard': assume free travel? (boolean) - default: false
*
* TODO: Add support for notices/detection about invalid connections
*/
function getTrips($from, $to, $options = array()) {
if (!empty($options['dateTime'])) {
$options['dateTime'] = date('c', strtotime($options['dateTime']));
}
$xmlTree = $this->getUrl('ns-api-treinplanner', array_merge(array('fromStation' => $from, 'toStation' => $to), $options));

$output = array();
// Loop over each option
foreach($xmlTree as $xmlTrip) {
$trip = (array) $xmlTrip;
$tripOption = array('duration_scheduled' => self::hourMinutesToSeconds($trip['GeplandeReisTijd']),
'duration_actual' => self::hourMinutesToSeconds($trip['ActueleReisTijd']),
'optimal' => $trip['Optimaal'], 'departure_actual' => $trip['ActueleVertrekTijd'], 'departure_scheduled' => $trip['GeplandeVertrekTijd'],
'departure_actual' => strtotime($trip['ActueleVertrekTijd']), 'departure_scheduled' => strtotime($trip['GeplandeVertrekTijd']),
'arrival_actual' => strtotime($trip['ActueleVertrekTijd']), 'arrival_scheduled' => strtotime($trip['GeplandeVertrekTijd']),
'changes' => $trip['AantalOverstappen']
);

// Loop over each part of the option
foreach ($xmlTrip->ReisDeel as $xmlPart) {
$part = (array) $xmlPart;
$stops = array();

// Loop over each stop
foreach ($xmlPart->ReisStop as $xmlStop) {
$stop = (array) $xmlStop;
$curStop = array('station' => $stop['Naam'], 'time' => strtotime($stop['Tijd']));
if (!empty($stop['Spoor'])) {
$curStop['platform'] = $stop['Spoor'];
}
$stops[] = $curStop;
}

$tripOption['connections'][] = array('mode' => strtolower($part['@attributes']['reisSoort']),
'type' => $part['VervoerType'], 'service' => $part['RitNummer'], 'stops' => $stops);
}
$output[] = $tripOption;
}
return $output;
}

/*
* Get a list of prices for a give to/from trip
* Lists class as 1 or 2 (first/second) and discount as (0, 20 or 40%)
*/
function getPrices($from, $to, $via = null) {
$xmlTree = $this->getUrl('ns-api-prijzen-v2', array('from' => $from, 'to' => $to, 'via' => $via));

$output = array();
foreach($xmlTree->Product as $product) {
$productArray = (array) $product;
foreach ($product->Prijs as $price) {
$price = (array) $price;
switch ($price['@attributes']['korting']) {
case "reductie_20": $discount = 20; break;
case "reductie_40": $discount = 40; break;
case "vol tarief": $discount = 0; break;
default: $discount = 0; break;
}
$output[] = array('product' => $productArray['@attributes']['naam'],
'class' => $price['@attributes']['klasse'], 'discount' => $discount, 'price' => $price[0]);
}
}

return $output;
}

// UTILITY FUNCTIONS

/*
* Convert hours and minutes seperated by a colon to seconds
*/
private function hourMinutesToSeconds($input) {
$input = explode(':', $input);
return 60*($input[1]+ ($input[0]*60));
}

/*
* Internal functioning for downloading data
* TODO: Add support for HTTPS and/or CURL
*/
private function getUrl($endpoint, $vars = array()) {

// Write query string
$query = "?";
foreach($vars as $key => $value) {
if ($value != "") {
$query .= $key."=".urlencode($value)."&";
}
}
$query = rtrim($query, '&');
$url = self::$base_url . $endpoint . $query;

// Create context to be able to specify authentication
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Basic " . base64_encode($this->authUser.":".$this->authPassword)
)
));
$data = file_get_contents($url, false, $context);
if (!$data)
return false;

// Parse the result
$xmlTree = simplexml_load_string($data);

return $xmlTree;
}

}

?>

<?PHP
//DATUM NL
  $tijd = date("H:i");
  $dag_vd_week = date("w");
  $maand_vh_jaar = date("n")-1;
  $dedag = date("j");
  $jaar = date("Y");
  $uur = explode(":", $tijd);

  $dagen = array('Zondag', 'Maandag', 'Dinsdag', 'Woensdag', 'Donderdag', 'Vrijdag', 'Zaterdag');
  $maanden = array('januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september', 'oktober', 'november', 'december');
  $dag = $dagen[$dag_vd_week];
  $maand = $maanden[$maand_vh_jaar]; 


//STATIONS VARS
$station = $_GET['from'];
$station = stripslashes($_GET['from']);
$stationnaam = urlencode($station);

include './js/sec.php';
?>
<?php
//Haal het bestand op
$xml_feed4 = file_get_contents('http://www.ns.nl/storingen/index.rss');
//Een XML phraser aanmaken
$xml_praser4 = xml_parser_create();
//Verwerking
xml_parse_into_struct($xml_praser4,$xml_feed4,$xml_sleutel,$xml_index);
xml_parser_free($xml_praser4);
//Genereren van headlines
for($s = 0; !empty($xml_index['TITLE'][$s]); $s++){

	if ($s == 0) {
	$storing = 0;
	}if ($s == 1) {
	$storing =  1;
	$storing1 = $xml_sleutel[$xml_index['TITLE'][1]]['value'];
	$naam = $storing1;
	}if ($s > 1) {
	$storing =  $s;
	}
}
?>
<div id="textbox">
  <p class="alignleft">Station <?PHP echo $station; ?></p>
  <p class="alignright"><?PHP echo "$dag $dedag $maand $jaar - $tijd"; ?></p>
</div><div style="clear: both;"></div>
<?PHP 
if($storing == 1) { 
echo "<div id='storing'>Er is op dit moment 1 storing bekend!</div>";
}
if($storing > 1) {
echo "<div id='storing'>Er zijn op dit moment $storing storingen bekend!</div>";
}
?>
<table cellpadding="0" cellspacing="0" style="width: 100%; color: #FFFFFF; background-color: #18295B;">
<td width="5px"></td><td width="70px"><div id="top_tijd">Vertrek</div></td><td width="450px"><div id="top_bestemming">Naar / Bestemming</div></td><td width="58px"><div id="top_spoor">Spoor</div></td><td width="80px"><div class="top_soort">Trein</div></td><td><div class="top_opmerking">Opmerkingen</div></td>
</table>
<table cellpadding="0" cellspacing="0" style="width: 100%; color: #FFFFFF;">
<?PHP
	require('php_ns_trains.class.php');
	define(API_USER, '*********');
	define(API_PASSWORD, '*********');
	$ns = new PhpNsTrains(API_USER, API_PASSWORD);
		
		
		foreach($ns->getDepartures($stationnaam) as $train) {
			$vertrektijd = date('H:i', $train['departure']);
			$soort = $train['type'];
			$ritnummer = $train['service'];
			$via = $train['via'];
			$vervoerder = $train['carrier'];
			$bestemming = $train['destination'];
			$spoor = $train['platform'];
			$vertrekspoor = strtolower($spoor); 
			$vertraging = $train['delay'];
			$spoorw = $train['platform_changed'];
			$cancelled = $train['cancelled'];
			$comment = $train['comments'];   
		
				$i++;		
 					if($soort == ""){
						$soort = "Trein";
					}
					if($cancelled == "true"){
						$weg = true;
                        $vertraging = 0;
						$vertrekspoor = "leeg";
					}else{
						$weg = false;
					}

					if($soort == "CityNightLine"){
						$soort = "NightLine";
					}
					if($soort == "SPR"){
						$soort = "Sprinter";
					}
					if($soort == "Stopbus i.p.v. Trein"){
						$vertrekspoor = "leeg";
						$soort = "Bus";
					}
					if($soort == "Snelbus i.p.v. Trein"){
						$vertrekspoor = "leeg";
						$soort = "Bus";
					}
					if($bestemming == "Den Haag C / Rotterdam C"){
						$bestemming = "Den Haag CS / Rotterdam CS";
					}
					if($spoorw == "true") {
						$swijziging = "true";
						$swijzigingtekst = "Spoor Gewijzigd!";
					}else{
						$swijziging = false;
					}


							$delay = $vertraging * 60;
							$time2 = strtotime($vertrektijd);
							$time2 = date("H:i", $time2 + $delay);

							$orgi = date("H:i");
							$orgi = strtotime($orgi);
							$time3 = strtotime($vertrektijd);
							$time3 = date("i", $time3 - $orgi);
							$time33 = str_replace("0", " ", "$time3");
					if($i < 16){
					
						$background=($i&1)?"":"&amp;achtergrond=wit";
						?>	               
				
				
    	<tr class="row<? echo ($i&1); ?>">
        	<td width="65px">
		<?PHP
		if($vertraging > 1){
		?>
		<div id="tijdw"><?php echo $time2; ?></div>
		<div id="tijdw2"><?php echo "was: $vertrektijd"; ?></div>
		<?PHP
		}else{
		?>
		<div class="vertrektijd"><?php echo $vertrektijd; ?></div>
		<?PHP
		}
		?>
		</td>
            <td width="450px">
	<?PHP
	if ($weg == true){
	?>
	<div id="bestemming"><s><?php echo "<a href='./fullscreen.php?from=$bestemming'>$bestemming</a>"; ?></s></div>
	<?PHP
	}else{
	?>
	<div id="bestemming"><?php echo "<a href='./fullscreen.php?from=$bestemming'>$bestemming</a>"; ?></div>
	<?PHP
	}
	?>
       <div class="naar_via_opm"><?PHP echo $via;  ?></div></td>
       <?PHP if($swijziging == true){ ?>
            <td width="50px";><img border="2" style="border-color:red; border-left:0; border-top:0;" src="./sporen/<?php echo $vertrekspoor; ?>.png"></td>
       <?PHP }else{ ?>
       		<td width="50px";><img src="./sporen/<?php echo $vertrekspoor; ?>.png"></td>
       <?PHP } ?>

		<td width="80px";><div id="soort"><?PHP echo $soort; ?><br /><font size="1"><?php echo $ritnummer; ?></font></div></td>
        												<td><?php
										if($swijziging == true){
										?>
										<div id="wijzigingspoor"><?php echo "<b>Let op:</b><font color='red'> <u>Spoorwijziging!</u></font>"; ?></div>
										<?php
										}
										?>
                                                                       <?php
										if($weg == true){
										?>
										<div id='rijdtniet'><?php echo "Deze trein rijdt vandaag niet"; ?></div>
										<?php
										}
										?>
										<?php
										if($vertraging > 1){
										?>
										<div id="vertraging"><?php echo "+ $vertraging minuten vertraging"; ?></div>
										<?php
										}
										?>
										<?php
										if($soort == Bus){
										?>
										<div id="bus">Op dit traject vindt busvervoer plaats</div>
										<?php
										}
										?>

																		
</td>
        </tr>

<?PHP
}
}
if ($i < 2) {
?>
<tr class="row">
<td width="65px"><?php echo "<b>00:00</b>"; ?></td>
<td width="450px"><?php echo '<b><font color="red">Geen informatie beschikbaar</font></b>'; ?></td>
<td><img src="./sporen/leeg.png" /></td>
<td>ER01</td>
<td><?PHP echo '<b>Er is op dit moment geen actuele informatie beschikbaar...</b>'; ?></td>
<td>
</tr>						 
<?PHP
}
?>
</table>



Leuk dat je een lap code post (zie ook mijn modedit hierboven), maar we werken hier niet als een afhaalbalie. ;-)
Ik heb je net verteld hoe je die kan inbouwen, dus probeer het eens.
Hallo is er een manier om de actuele vertrektijden van bijvoorbeeld van Gouda Goverwelle op twitter te laten zien.
Op wat voor manier? Wou je 8 tweets per uur plaatsen met de recente vertrektijden?

Onthoud wel dat plaatsen van een hoop tweets in een uur een blokkade kan opleveren, vanwege spamming, mocht je het uit willen breiden naar meerdere stations.

Ik wil alleen zeg maar als er vertraging is of een spoorwijziging of dat hij niet rijd dat er dan een tweet van komt.
Dat kan je doen, een kwestie van uitlezen met SimpleXML, en bij een afwijking (Opmerkingen-elementen/of vertraging) een tweet plaatsen. Om tweets te plaatsen gebruik ik: https://github.com/abraham/twitteroauth. Sla ook even de treinnummers in de database op om te voorkomen dat inmiddels getweette berichten niet nogmaals getweet worden.

Maar begin bij het begin en probeer eerst maar eens de XML uit te lezen met SimpleXML.
Ik ga dat vanavond of morgen even er na kijken.
Hallo

hier ben ik weer ik had een vraag hoe moet ik de dvs laten zien ik heb een ovh vps server maar daar haalt hij geen bestanden op en stefan van opengeo zegt met deze >>> curl http://acc.data.ndovloket.nl/
Voor de niet-ingewijden hier: De DVS staat los van de NS-API en wordt via een TCP-verbinding verspreid naar het NDOV-loket, waar klanten deze data kunnen afnemen. Ze dienen zelf een API te bouwen, en daarvoor kan gebruik worden gemaakt van dit Python-script.
De DVS is de directe datastroom die ze ook gebruiken op de informatieborden etc. en komt direct bij de treindienstleiding vandaan, i.p.v. uit een planning, zoals bij de NS-API

Ikzelf heb het geheel al draaiende gekregen op een test-server, en de output krijg ik netjes in JSON-formaat.
Een voorbeeld kan je vinden op [url=http://dvsrdt.pellegrom.org/station/wd]deze link.

Reageren