Reputation: 609
I am new to php, therefore I have got a beginner question. I did a text file with some simple data in it and I would like to save that data into a xml file.
I have tried it with a foreach loop, but I struggle at this point. I know what the problem is, but I am to stupid to fix ist.
Here is my text file:
Lea
mueller
[email protected]
10.03.1984
green
Malte
cool
äödksf@kdölf.com
23.12.54
red
Peter
Pam
ö[email protected]
23.23.2323
pink
My php:
<?php
$file = file("daten.txt");
$dom = new DOMDocument('1.0', 'utf-8');
$data = $dom->createElement('data');
$dom->appendChild($data);
foreach($file as $value){
$user = $dom->createElement("user");
$data->appendChild($user);
$vorname = $dom->createElement("vorname", "$value");
$user->appendChild($vorname);
$nachname = $dom->createElement("nachname", "$value");
$user->appendChild($nachname);
$email = $dom->createElement("email", "$value");
$user->appendChild($email);
$bday = $dom->createElement("bday", "$value");
$user->appendChild($bday);
$color = $dom->createElement("color", "$value");
$user->appendChild($color);
}
$dom->save("new.xml");
print_r($file);
?>
I always get the name, lastname, email, bday and color four times. I know why, but I dont know, how I can do it in another way?
Upvotes: 0
Views: 160
Reputation: 733
In that code you got there, it appears to me that you used $value multiple times hoping it changes to the next line, I think it wouldn't
Try replacing your foreach loop with this:
for ($x = 0; $x<count($file); $x+=5){
$user = $dom->createElement("user");
$data->appendChild($user);
$vorname = $dom->createElement("vorname", trim($file[$x]));
$user->appendChild($vorname);
$nachname = $dom->createElement("nachname", trim($file[$x+1]));
$user->appendChild($nachname);
$email = $dom->createElement("email", trim($file[$x+2]));
$user->appendChild($email);
$bday = $dom->createElement("bday", trim($file[$x+3]));
$user->appendChild($bday);
$color = $dom->createElement("color", trim($file[$x+4]));
$user->appendChild($color);
}
Also, please fix your indentations.
Let me know if this works.
Edit: Fixed semicolon usage in loop condition.
Upvotes: 1