<customers>
    <customer>
        <ID>C1</ID>
        <FirstName>Jack</FirstName>
        <SurName>Wong</SurName>
        <Email>jack@hotmail.com</Email>
        <Password>081292</Password> 
    </customer> 

    <customer>
        <ID>C2</ID>
        <FirstName>Ashley</FirstName>
        <SurName>Rachael</SurName>
        <Email>ashley@hotmail.com</Email>
        <Password>081292</Password> 
    </customer>

    <customer>
        <ID>C3</ID>
        <FirstName>Vongola</FirstName>
        <SurName>Steve</SurName>
        <Email>vongola@hotmail.com</Email>
        <Password>081292</Password> 
    </customer>
</customers>

I have a existing xml showing like that.
I did some research through net, but they all were talking about one element. For example <Email>xxx@hotmail.com</Email>

But what if I want add all those ID tag, FirstName tag, SurName tag, etc into Customer tag and Customer tag into Customers tag?

Thanks for in advance.

Hi,

once you load the document, create an element (customer) inside the root (customers), then create the children elements of customer and append them to it, at the end append the customer element to the root. Basically:

<?php

$str = <<<'XML'
<customers>
    <customer>
        <ID>C1</ID>
        <FirstName>Jack</FirstName>
        <SurName>Wong</SurName>
        <Email>jack@hotmail.com</Email>
        <Password>081292</Password> 
    </customer> 

    <customer>
        <ID>C2</ID>
        <FirstName>Ashley</FirstName>
        <SurName>Rachael</SurName>
        <Email>ashley@hotmail.com</Email>
        <Password>081292</Password> 
    </customer>

    <customer>
        <ID>C3</ID>
        <FirstName>Vongola</FirstName>
        <SurName>Steve</SurName>
        <Email>vongola@hotmail.com</Email>
        <Password>081292</Password> 
    </customer>
</customers>
XML;

$dom = new DOMDocument();
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($str);
$dom->formatOutput = TRUE;

$customers = $dom->documentElement;
$customer  = $dom->createElement("customer");

$data = ['ID'        => 'C4'
       , 'FirstName' => 'Name'
       , 'SurName'   => 'Last Name'
       , 'Email'     => 'email address here'
       , 'Password'  => 'really?!'];

foreach($data as $k => $v)
{
    $el = $dom->createElement($k, $v);
    $customer->appendChild($el);
}

$customers->appendChild($customer);
print $dom->saveXML();

See:

The Daniweb link is about an HTML document, it uses the same rules for XML documents and it explains how to apply attributes to the elements.

To open an save to a file, use these methods :

Bye!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.