使用PHP Dom将单个元素/单个标记添加到XML结构

时间:2016-09-21 07:47:28

标签: php dom

我尝试使用PHP Dom将没有结束标记的单个元素/单个标记添加到XML结构中,以获得类似这样的内容:

{{1}}

有人知道我可以使用哪个命令来获取此信息吗?

1 个答案:

答案 0 :(得分:0)

$domDocument = new \DOMDocument('1.0', 'UTF-8');
$rootNode = $domDocument->createElement('ndxml');
$credentials = $domDocument->createElement('credentials');
$credentials->appendChild(new \DOMElement('identity', 'User'));
$credentials->appendChild(new \DOMElement('password', 'Password'));
$language = $domDocument->createElement('language');
$language->setAttribute('name', 'default');
$language->setAttribute('modifier', 'de');
$credentials->appendChild($language);

$rootNode->appendChild($credentials);
$domDocument->appendChild($rootNode);

echo $domDocument->saveXML();
echo "\n\n";

echo $domDocument->saveXML(null, LIBXML_NOEMPTYTAG);

输出:

<?xml version="1.0" encoding="UTF-8"?>
<ndxml><credentials><identity>User</identity><password>Password</password><language name="default" modifier="de"/></credentials></ndxml>


<?xml version="1.0" encoding="UTF-8"?>
<ndxml><credentials><identity>User</identity><password>Password</password><language name="default" modifier="de"></language></credentials></ndxml>