简体   繁体   English

使用PHP创建XML文件

[英]create XML File using PHP

I want to create a XML File (1.0) via PHP but I have problems with using DOMDocument . 我想通过PHP创建XML文件(1.0),但使用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'. 如您所见,它不会显示诸如“ client”和“ exampleClient”之类的createElement()数据。

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 : 您缺少将$client$clientID附加到$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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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