Q . PHP xmlwriter - write element with attribute.

Brad Johnson. asked, Oct 24 ' 2017

I am writing xml using php. I want to write attribute with element. My code is as below

$writer = new XMLWriter();  
$writer->openURI('php://output');   
$writer->startDocument('1.0','UTF-8');   
$writer->setIndent(4);   
$writer->startElement('Response');
$writer->writeElement("Dial","+111111111");
$writer->endElement();
$writer->endDocument();   
$writer->flush();

Output

<response>
<dial>+111111</dial>
</response>

But I want something like this

<response>
<dial action="myaction">+111111</dial>
</response>

I tried this

$writer->writeAttribute('action', 'myaction');

But this work only with startElement not with writeElement.

  • PHP
  • xml
  • php-xmlwriter

1 Answers

Instead line $writer->writeElement("Dial","+111111111"); 

you should write the element in some steps to add attribute

$writer->startElement("Dial");
$writer->writeAttribute('action', "myaction");
$writer->text("+111111111");
$writer->endElement();

 

Leave a Ansewer