简体   繁体   中英

PHP: How to add attributes to the deeper child note with SimpleXMLElement

How can I add attributes to the deeper child note with SimpleXMLElement ? for instance,

$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());

I get this,

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

But actually I want,

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

Is it possible?

<?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());

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