Question

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?

Was it helpful?

Solution

<?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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top