PHP :: Aufgabe #3 :: Lösung #1

3 Lösungen Lösungen öffentlich
#3

CSV-Datei auslesen und aus den Daten eine Tabelle und ein Diagramm erzeugen

Fortgeschrittener - PHP von Gustl - 16.08.2012 um 10:35 Uhr
Erstellen Sie ein PHP- Skript, das die angehängte CSV- Datei (EUR/USD Dollarkurs von einem Jahr) in ein Array einliest. Diese eingelesenen Werte sollen in einer Tabelle dargestellt werden und sich in einem Linien-, Punkt- oder Balkendiagramm widerspiegeln.

In dem Diagramm soll nur jeder vierte Wert ausgegeben werden.
Das Datum soll in folgendes Format konvertiert werden: DD.MM.YY (16.08.12)


#1
vote_ok
von alxy (60 Punkte) - 17.08.2012 um 01:30 Uhr
Quellcode ausblenden PHP-Code
<?php

class Csv
{

	protected $csvArray		=	array();
	protected $htmlTable	=	'';
	
	public function __construct( $file )
	{
	
		$this->importCsvData( $file );
		$this->makeTable( $this->csvArray );
		
	}
	
	protected function importCsvData( $file )
	{
	
		$handle	=	fopen( $file, 'r' );
		
		while( ($line = fgetcsv( $handle, 0, ';' )) !== FALSE ){
		
			$this->csvArray[]	=	$line;
			
		}
		
		fclose($handle);
		
		$this->csvArray	=	$this->modifyArray( $this->csvArray );
		
	}
	
	protected function modifyArray( array$array )
	{
	
		foreach ( $array as &$subarray ) {
		
			$keys	=	array_keys( $subarray, NULL );
			
			foreach ( $keys as $key ) {
			
				unset( $subarray[$key] );
				
			}
			
			if ( isset($subarray[0]) ) {
			
				$subarray[0]	=	$this->formatDate( $subarray[0] );
				
			}
			
		}
		
		return $array;
		
	}
	
	protected function formatDate( $date )
	{
	
		if ( $this->isValidDate( $date ) ) {
		
			$oDateTime	=	new DateTime( $date );
			return $oDateTime->format( 'd.m.y' );
		
		}
		
		return $date;
		
	}
	
	protected function isValidDate( $str )
	{
		  $stamp = strtotime( $str );
		 
		  if (!is_numeric($stamp))
		  {
			 return FALSE;
		  }
		  $month = date( 'm', $stamp );
		  $day   = date( 'd', $stamp );
		  $year  = date( 'Y', $stamp );
		 
		  if (checkdate($month, $day, $year))
		  {
			 return TRUE;
		  }
		 
		  return FALSE;
	} 
	
	protected function makeTable( array$array )
	{
	
		$html	=	'<table>';
		
		foreach ( $array as $subarray ) {
		
			$html	.=	'<tr>';
			
			foreach ( $subarray as $value ) {
			
				$html	.=	'<td>' . $value . '</td>';
				
			}
			
			$html	.=	'</tr>';
			
		}
		
		$html	.=	'</table>';
		
		$this->htmlTable	=	$html;
	
	}
	
	public function printArray()
	{
	
		return $this->csvArray;
		
	}
	
	public function printTable()
	{
	
		return $this->htmlTable;
		
	}
	
}

$csv	=	new Csv( 'csv.csv' );

echo $csv->printTable();

		


Das mit dem Diagramm habe ich jetzt nicht verstanden... soll das auch mit PHP umgesetzt werden?

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben