PHP vraagje

Status
Niet open voor verdere reacties.
Wat dacht je er van om een print_r te doen van die array. kun je de keys en values bekijken.
 
Dat weet ik maar als ik dat doet zie ik de reistip niet.

dit is een stukje code er van

<?php
}
foreach ((array) $comment as $ReisTip)
{
?>
<div id="ReisTip"><?php echo $comment; ?></div>
 
Laatst bewerkt:
een wilde gok, ik weet niet hoe je array opgebouwd is. maar controleer je complete array. ik denk dat je dan in een verkeerd key aan het kijken bent
 
Code:
<?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 / Opmerkingen</div></td><td width="58px"><div id="top_spoor">Spoor</div></td><td width="80px"><div class="top_soort">Trein</div></td>
<td width="569"><div class="top_opmerking">Opmerkingen</div></td><td></td><div id="mat">Materiaal</div></td>
</table>
<table cellpadding="0" cellspacing="0" style="width: 100%; color: #FFFFFF;">
<?PHP
	require('php_ns_trains.class.php');
	define(API_USER, 'xxxxx');
	define(API_PASSWORD, 'xxxxx');
	$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'];
           	        $ReisTip = $train['ReisTip'];
                        $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="50px";><img src="./images/carrier/<?php echo $vervoerder; ?>.png"></td>
		    <td width="80px";><div id="soort"><img src="./images/mat/<?php echo $soort; ?>.png"><br /><font size="1"> <td width="80px";><?php echo $ritnummer; ?></font></div></td>
        												<td><?php
										if($swijziging == true){
										?>
										<div id="wijzigingspoor"><?php echo "<font color='blue'> <u>Spoorwijziging, vertrekt van spoor $vertrekspoor "; ?></u></font></div>
										<?php
										}
										?>
                                                                       <?php
										if($weg == true){
										?>
										<div id='rijdtniet'><?php echo "Trein rijdt 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
										}
										?>
                                        <?php
										if($soort == ReisTip){
										?>
										<?php
										}
										foreach ((array) $comment as $ReisTip)
								        {
								        ?>
								        <div id="ReisTip"><?php echo $comment; ?></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="./img/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>

dit is de hele php script er van
 
leuk die code, maar dat laat niet zien welke array of json je ontvangt en hoe die opgebouwd is.
 
<div id="ReisTip"><?php echo $comment; ?></div>
maak van $comment eens $ReisTip

en

if($soort == ReisTip){
moet if($soort == $ReisTip){ worden
 
$comment = $train['comments']; dit is de array welke je met $ReisTip uit leest en op het scherm zet.

Als $comment = $train['comments']; niet de data is die je zoekt, dan moet je in de array $train gaan zoeken naar de array key welke wel de data bevat die je zoekt
 
echo "<pre>";
print_r($train);
echo "</pre>";
en kijk welke data je krijgt en waar de data in je multi-array staat
 
dit is wat ik krijg van de prnit_r($train);
Array ( [departure] => 1406927040 [service] => 3091 [destination] => Nijmegen [carrier] => NS [type] => Intercity [platform] => 2 [via] => Alkmaar, Amsterdam C., Utrecht C [platform_changed] => [ReisTip] => [comments] => Array ( [0] => ) [cancelled] => ) Array ( [departure] => 1406930220 [service] => 4095 [destination] => Amsterdam Centraal [carrier] => NS [type] => Sprinter [platform] => 2 [via] => Alkmaar, Uitgeest, Zaandam [platform_changed] => [ReisTip] => [cancelled] => ) Array ( [departure] => 1406932440 [service] => 3097 [destination] => Alkmaar [carrier] => NS [type] => Intercity [platform] => 3 [via] => [platform_changed] => [ReisTip] => [comments] => Array ( [0] => ) [cancelled] => ) Array ( [departure] => 1406954040 [service] => 3025 [destination] => Nijmegen [carrier] => NS [type] => Intercity [platform] => 2 [via] => Alkmaar, Amsterdam C., Utrecht C [platform_changed] => [ReisTip] => [comments] => Array ( [0] => ) [cancelled] => ) Array ( [departure] => 1406955840 [service] => 3027 [destination] => Nijmegen [carrier] => NS [type] => Intercity [platform] => 3 [via] => Alkmaar, Amsterdam C., Utrecht C [platform_changed] => [ReisTip] => [comments] => Array ( [0] => ) [cancelled] => ) Array ( [departure] => 1406957640 [service] => 3029 [destination] => Nijmegen [carrier] => NS [type] => Intercity [platform] => 3 [via] => Alkmaar, Amsterdam C., Utrecht C [platform_changed] => [ReisTip] => [comments] => Array ( [0] => ) [cancelled] => ) Array ( [departure] => 1406959440 [service] => 3031 [destination] => Nijmegen [carrier] => NS [type] => Intercity [platform] => 2 [via] => Alkmaar, Amsterdam C., Utrecht C [platform_changed] => [ReisTip] => [comments] => Array ( [0] => ) [cancelled] => ) Array ( [departure] => 1406961240 [service] => 3033 [destination] => Nijmegen [carrier] => NS [type] => Intercity [platform] => 2 [via] => Alkmaar, Amsterdam C., Utrecht C [platform_changed] => [ReisTip] => [comments] => Array ( [0] => ) [cancelled] => ) Array ( [departure] => 1406963040 [service] => 3035 [destination] => Nijmegen [carrier] => NS [type] => Intercity [platform] => 3 [via] => Alkmaar, Amsterdam C., Utrecht C [platform_changed] => [ReisTip] => [comments] => Array ( [0] => ) [cancelled] => ) Array ( [departure] => 1406964840 [service] => 3037 [destination] => Nijmegen [carrier] => NS [type] => Intercity [platform] => 2 [via] => Alkmaar, Amsterdam C., Utrecht C [platform_changed] => [ReisTip] => [comments] => Array ( [0] => ) [cancelled] => )
 
Dan is die leeg? Weet je zeker dat er wat in hoort te staan?

En als dit om de NS API gaat, waarom gebruik je niet gewoon meteen json_encode()?
 
Laatst bewerkt:
Kijken naar www.php.net/json_decode

Daar staat de werking uitgelegd. Op internet staan ook een hoop tutorials over de werking van Json en het uitlezen ervan.
Als het XML is dan moet je kijken naar SimpleXML.

Ik weet niet hoe de NS API werkt verder, maar hiermee kan je verder gaan.
Alleen even kijken of het JSON of XML is ;)

Ik heb even gekeken, en het wordt in XML aangeboden.
 
Laatst bewerkt:
Dat zijn PHPfuncties ja, die je kan gebruiken. Kijk eens naar SimpleXML....
 
en het wordt zo aangevoerd.

Code:
<?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-v2');
		
		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
	 */
	function getDepartures($station, $key = null) {
		$xmlTree = $this->getUrl('ns-api-avt', array('station' => $station));
		$output = array();
		// 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'], 'carrier' =>  $train['Vervoerder'], 'type' => $train['TreinSoort'], 
				'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;
			   $add['ReisTip'] = $ReisTip; print_r($reistip);
		foreach($xmlTrain->ReisTip as $comment) {
				                $text = trim((string) $comment->ReisTip);
				                if ($text == "Stopt niet in Arnhem Zuid") {
					                    $ReisTip = true;
				               }
				               $add['comments'][] = $text;
			             }
			                   $add['cancelled'] = $cancelled;
		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."=".$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;
	}

}

?>
 
Status
Niet open voor verdere reacties.

Nieuwste berichten

Terug
Bovenaan Onderaan