read/write xml file in php, task
This commit is contained in:
70
Zweites Jahr/aufgaben/csvToXml/convertCSVtoXML.php
Normal file
70
Zweites Jahr/aufgaben/csvToXml/convertCSVtoXML.php
Normal file
@@ -0,0 +1,70 @@
|
||||
<h1>CSV -> XML</h1>
|
||||
<?php
|
||||
|
||||
error_reporting(E_ALL);
|
||||
ini_set("display_errors", 1);
|
||||
|
||||
// DOM struktur
|
||||
/*
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<personen>
|
||||
<nr> </nr>
|
||||
<vorname> </vorname>
|
||||
<nachname> </nachname>
|
||||
</personen
|
||||
*/
|
||||
|
||||
// READ CSV FILE
|
||||
$fileCSV = "e2fi2.csv";
|
||||
if(!file_exists($fileCSV)){
|
||||
die("File $fileCSV doesn't exist or not found!");
|
||||
}
|
||||
|
||||
$fp = @fopen($fileCSV, 'r');
|
||||
if(!$fp){
|
||||
die("Error while opening CSV file!");
|
||||
}
|
||||
$header_array =fgetcsv($fp, 0, ";");
|
||||
|
||||
|
||||
print_r($header_array);
|
||||
|
||||
// CREATE XML DOM
|
||||
$xmlDoc = new DOMDocument("1.0", "utf-8");
|
||||
$xmlDoc->formatOutput=true;
|
||||
|
||||
$xmlRoot = $xmlDoc->createElement("data");
|
||||
$xmlDoc->appendChild($xmlRoot);
|
||||
|
||||
|
||||
// FILL XML FILE WITH CSV DATA
|
||||
while(($row_array = fgetcsv($fp, 0, ";")) !== false){
|
||||
// skip emty value
|
||||
if ($row_array === null || $row_array === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// create sub elemente
|
||||
$xmlSchueler = $xmlDoc->createElement("schuelerdata");
|
||||
// for the count of elements in a row do this
|
||||
for ($i = 0; $i < count($row_array); $i++){
|
||||
// make sure there is a header to row
|
||||
if (!isset($header_array[$i])){
|
||||
continue;
|
||||
}
|
||||
|
||||
// get current collumn
|
||||
$column = $header_array[$i];
|
||||
echo "$row_array[$i]<br>";
|
||||
|
||||
// create a new element with name of column and row data
|
||||
$xmlSchuelerDaten = $xmlDoc->createElement($column, $row_array[$i]);
|
||||
$xmlSchueler->appendChild($xmlSchuelerDaten);
|
||||
}
|
||||
// save element
|
||||
$xmlRoot-> appendChild($xmlSchueler);
|
||||
}
|
||||
|
||||
// Save whole XML file
|
||||
$fileXml = "e2fi2.xml";
|
||||
$xmlDoc->save(__DIR__ . "/$fileXml");
|
||||
Reference in New Issue
Block a user