简体   繁体   中英

Convert text file into xml

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
lea_mueller@web.de
10.03.1984
green
Malte
cool
äödksf@kdölf.com
23.12.54
red
Peter
Pam
ödlfs@we.de
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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM