简体   繁体   中英

create XML File using PHP

I want to create a XML File (1.0) via PHP but I have problems with using DOMDocument .

My code:

<?php
header('Content-Type:text/xml');
$xml = new DOMDocument('1.0', 'utf-8');
$root = $xml->createElement('root');
$root->setAttribute('id', '1234');
$root->setAttribute('date', '26.02.2018');
//info
$xml->appendChild($root);
$info = $xml->createElement('information');
$root->appendChild($info);
//updates
$updates = $xml->createElement('updates');
$info->appendChild($updates);
//updated
$updated= $xml->createElement('updated');
$updates->appendChild($updated);
//client
$client = $xml->createElement('client', 'exampleClient');
$updates->appendChild($updated);
//clientID
$clientID = $xml->createElement('clientID', '123456');
echo $xml->saveXML();
?>

Output:

<root id="1234" date="26.02.2018">
    <information>
        <updates>
            <updated/>
        </updates>
    </information>
</root>

As you can see, it doesn't display the createElement() Data like 'client' and 'exampleClient'.

My desired output:

<root id="1234" date="26.02.2018">
<information>
    <updates>
        <updated>
            <client>exampleClient</client>
            <clientID>123456</clientID>
        </updated>
    </updates>
</information>
</root>

Does anyone have any idea how I can solve the problem?

You're missing to append $client and $clientID into $updated :

$updated->appendChild($client);
$updated->appendChild($clientID);
echo $xml->saveXML();

You Can also use code to get your answer

$xml = new SimpleXMLElement('<root/>');

    $xml->addAttribute( "id", "123" );
    $xml->addAttribute("date", "26.02.2018" );
    $information = $xml->addChild('information');
    $updates = $information->addChild('updates');
    $updated = $updates->addChild('updated');
    $client = $updated->addChild('client','exampleClient');
    $clientID = $updated->addChild('clientID','123456');
Header('Content-type: text/xml');
print($xml->asXML());

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