Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent self closing tag in php simplexml

Tags:

php

xml

simplexml

I want to generate xml by using php simplexml.

$xml = new SimpleXMLElement('<xml/>');

$output = $xml->addChild('child1');
$output->addChild('child2', "value");
$output->addChild('noValue', '');

Header('Content-type: text/xml');
print($xml->asXML());

The output is

<xml>
   <child1>
      <child2>value</child2>
      <noValue/>
   </child1>
</xml>

What I want is if the tag has no value it should display like this

<noValue></noValue>

I've tried using LIBXML_NOEMPTYTAG from Turn OFF self-closing tags in SimpleXML for PHP?

I've tried $xml = new SimpleXMLElement('<xml/>', LIBXML_NOEMPTYTAG); and it doesn't work. So I don't know where to put the LIBXML_NOEMPTYTAG

like image 298
Wakanina Avatar asked Oct 28 '13 07:10

Wakanina


People also ask

Which tag is not a self closing tag?

There are also tags that are forbidden to be closed: img, input, br, hr, meta, etc.

How do I close a self closing tag?

A self-closing tag is an element of HTML code that has evolved in the language. Typically, the self-closing tag makes use of a “/” character in order to effectively close out a beginning tag enclosed in sideways carets.

Which tag is self closing?

Self Closing HTML ElementsThe br tag inserts a line break (not a paragraph break). This tag has no content, so it is self closing.

Should I close self closing tags?

The fact is there is no need to close self closing tags by a slash /> at the end of the tag. Although many people use it but there is no meaning of slash at the end of the start tag even though you use it is ignored by the browsers.


1 Answers

Despite the quite lengthy answers already given - which are not particularly wrong and do shed some light into some libxml library internals and it's PHP binding - you're most likely looking for:

$output->noValue = '';

To add an open tag, empty node-value and end tag (beautified, demo is here: http://3v4l.org/S2PKc):

<?xml version="1.0"?>
<xml>
  <child1>
    <child2>value</child2>
    <noValue></noValue>
  </child1>
</xml>

Just noting as it seems it has been overlooked with the existing answers.

like image 128
hakre Avatar answered Sep 18 '22 15:09

hakre