PHP:如何使用SimpleXMLElement将属性添加到更深的子注释中

时间:2013-09-14 09:46:21

标签: php xml simplexml php-5.4

如何使用SimpleXMLElement向更深层的儿童音符添加属性?例如,

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

$response = $xml->addChild('response');
$response->addChild('error');
$response->addAttribute('elementid', 100);
$response->addAttribute('message', 'You must not leave this field empty!');


Header('Content-type: text/xml');
print($xml->asXML());

我明白了,

<xml>
<response elementid="100" message="Key name - You must not leave this field empty!">
<error />
</response>
</xml>

但实际上我想要,

<xml>
<response>
<error elementid="100" message="Key name - You must not leave this field empty!" />
</response>
</xml>

有可能吗?

1 个答案:

答案 0 :(得分:2)

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

$response   = $xml->addChild('response');
$error      = $response->addChild('error');
$error->addAttribute('elementid', 100);
$error->addAttribute('message', 'You must not leave this field empty!');

Header('Content-type: text/xml');
print($xml->asXML());