WME/aufgabe2/world_data_parser.php

77 lines
No EOL
2.1 KiB
PHP

<?php
class WorldDataParser {
function parseCSV($path) {
$res = [];
if (!is_file($path)) {
echo 'Datei nicht vorhanden! - ' . $path;
}
$handle = fopen($path, "r");
if ($handle !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$res[] = $data; // data array (aktueller Zeile) zu multidimensionalen array hinzufügen
}
fclose($handle);
} else {
echo 'Konnte Datei nicht öffnen! - ' . $path;
}
return $res;
}
function saveXML($data) {
$file = 'world_data.xml';
if (file_exists($file)) {
unlink($file);
}
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
$xml .= '<Countries>'. PHP_EOL;
foreach ($data as $zeilennummer => $csvzeile) {
if ($zeilennummer === 0) {
continue;
}
$xml .= " <Country>". PHP_EOL;
foreach ($csvzeile as $spaltennummer => $wert) {
$spaltenname = $data[0][$spaltennummer];
$spaltenname = trim($spaltenname);
$wert = trim($wert);
$spaltenname = str_replace(" ", "_", $spaltenname);
$xml .= " <". $spaltenname .">";
$xml .= $wert;
$xml .= "</". $spaltenname .">". PHP_EOL;
}
$xml .= " </Country>". PHP_EOL;
}
$xml .= '</Countries>'. PHP_EOL;
file_put_contents($file, $xml);
return file_exists($file);
}
function printXML($xml_file, $xslt_sheet) {
$xsl_doc = new DOMDocument();
$xsl_res = $xsl_doc->loadXML($xslt_sheet);
if ($xsl_res === false) {
echo "reading xsl sheet failed: {$xsl_res}";
return;
}
$xml_doc = new DOMDocument();
if ($xml_doc->loadXML($xml_file) === false) {
echo "reading world data xml failed";
return;
}
$xsl = new XSLTProcessor();
$xsl->importStyleSheet($xsl_doc);
echo $xsl->transformToXML($xml_doc);
}
}