-3

i need make a xml with php code, but i dont now how make a single node like <node/> using the xmlwriter method. example

<node>
     <element>ONE</element>
     <element>TWO</element>
     **<node_i_want_but_idontnow/>**
     <element>end</element>
</node>

Thanks in advance

  • Does this answer your question? [How to generate XML file dynamically using PHP?](https://stackoverflow.com/questions/486757/how-to-generate-xml-file-dynamically-using-php) – Vivek Mehta Jan 15 '20 at 05:37

1 Answers1

0

<node-name/> is just an optimization. If an element node has no child nodes (elements, text, comments, ...). it can be closed directly. For the parser it is the same as <node-name></node-name>.

The serializer will apply that optimization by default. However if you add an empty string as content you will create a text child node and block the optimization:

$writer = new XMLWriter();
$writer->openURI('php://stdout');
$writer->setIndent(2);
$writer->startDocument();
$writer->startElement('node');

// element with content
$writer->writeElement('element', 'one');
// empty element
$writer->writeElement('another_element');
// element with empty child node
$writer->writeElement('another_element', '');

$writer->endElement();
$writer->endDocument();

Output:

<?xml version="1.0"?>
<node>
 <element>one</element>
 <another_element/>
 <another_element></another_element>
</node>
ThW
  • 19,120
  • 3
  • 22
  • 44