<?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 read_file($path) {
        $fh = fopen($path, "rb");
        $data = fread($fh, filesize($path));
        fclose($fh);

        return $data;
    }

    function printXML($xml_file, $xslt_sheet) {
        $xsl_doc = new DOMDocument();
        if ($xsl_doc->loadXML($this->read_file($xslt_sheet)) === false) {
            echo "reading xsl sheet failed";
            return;
        }

        $xml_doc = new DOMDocument();
        if ($xml_doc->loadXML($this->read_file($xml_file)) === false) {
            echo "reading world data xml failed";
            return;
        }

        $xsl = new XSLTProcessor();

        $xsl->importStyleSheet($xsl_doc);
        $html = $xsl->transformToXML($xml_doc);

        echo $html;
    }
}