如何使用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>
有可能吗?
答案 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());