Creating XML node with null value in php

I am creating an xml file using php. The resulting XML file.

<xml> <data> <firstname>Peter</firstname> <insertion>V</insertion> <lastname>John</lastname> <gender>Male</gender> </data> </xml> 

But in the case where the value is null, the resulting xml is ( see node insertion ).

 <xml> <data> <firstname>Peter</firstname> <insertion/> <lastname>John</lastname> <gender>Male</gender> </data> </xml> 

If the value is null, I want the xml to be created so that it runs.

 <xml> <data> <firstname>Peter</firstname> <insertion></insertion> <lastname>John</lastname> <gender>Male</gender> </data> </xml> 

This is my code.

  $doc = new DOMDocument('1.0'); $doc->formatOutput = true; $root = $doc->createElement('data'); $doc->appendChild($root); $data = $doc->createElement('data'); $fname = $doc->createElement('firstname'); $fname->appendChild( $doc->createTextNode($row['firstname'])); $data->appendChild($fname); $ins = $doc->createElement('insertion'); $ins->appendChild( $doc->createTextNode($row['insertion'])); $data->appendChild($ins); $lname = $doc->createElement('lastname'); $lname->appendChild( $doc->createTextNode($row['lastname'])); $data->appendChild($lname); $gender = $doc->createElement('gender'); $gender->appendChild( $doc->createTextNode($row['gender'])); $data->appendChild($gender); $root->appendChild($data); $doc->save($path . "test.xml"); 

I am sending this xml as an answer after creating it. So, on the client side, lastname node becomes an insertion subnom when it

  <insertion/> 
+6
source share
1 answer

What is output by default is called the "abbreviated format". It is great for XML, and any properly implemented XML parser should be able to handle it just fine. The only reason I can think of forcing the output of "longhand" is because you need to feed the output XML to the parser, which is erroneous and cannot handle shorthand case. If you can replace the problematic parser with a working one, then I would recommend doing this.

If you absolutely need to output the version without abbreviations, the DOMDocument :: SaveXML () and DOMDocument :: save () methods allow you to customize their output. You can set a flag that causes the output to be verbose rather than abbreviated. However, this is not well documented in the PHP manual. The following code should show how it works.

 $dom = new DOMDocument (); $dom -> loadXML ('<root><foo>foo</foo><bar></bar><baz>baz</baz></root>'); var_dump ($dom -> saveXML ()); var_dump ($dom -> saveXML ($dom, LIBXML_NOEMPTYTAG)); 

Honestly, I don’t think it makes much sense to do this if the parser designed to work with your XML is not buggy.

0
source

All Articles