0

I am using simpleXMLElement to create a new xml file. I want to create something similar to the following:

<?xml version="1.0"?>
<command type="scenario" name="test">
    <game type="play" filename="google">
    </game>
</command>

I am using this code but something is not correct:

<?php

$xml = new SimpleXMLElement("<?xml version=\"1.0\" ?><command type='scenario'></command>"); 
$xml->addAttribute('name', 'test');
$game = $xml->addChild('game');
$game->addAttribute('type', 'play');
$game->addAttribute('filename', 'google');

// checking the output
$handler = fopen(sad.xml, 'w');
fwrite($handler, $xml->asXML());
fclose($handler);

?>

But this is the output i see in sad.xml file instead:

<?xml version="1.0"?>
<command type="scenario" name="test"><game type="play" filename="google"/></command>

Why?

  1. New lines are not appearing in the file
  2. game tag does not have </game> closing tag
hakre
  • 193,403
  • 52
  • 435
  • 836
Gago
  • 35
  • 2
  • 12
  • is there a reason you need it to output with the spaces and a full closing tag? As far as any XML parser will be concerned, those two documents are identical. – Chris Throup Jun 06 '13 at 18:24

2 Answers2

0

Try this.

$game = new SimpleXMLElement('', LIBXML_NOEMPTYTAG);    
$xml->addChild($game);

And you can find solutions for formatting output here PHP simpleXML how to save the file in a formatted way?

Community
  • 1
  • 1
aasiutin
  • 210
  • 2
  • 6
  • I am confused, please give a the code that would output what I asked. If it works I will accept your answer. Just edit it in you answer. Thanks – Gago Jun 06 '13 at 18:12
  • Also, when I add LIBXML_NOEMPTYTAG, I get number 4 in between ...??? – Gago Jun 06 '13 at 18:24
  • I just read that LIBXML_NOEMPTYTAG has a bug. So that is why I might get unexpected output. – Gago Jun 06 '13 at 18:27
0

@lexicus has explained how you could achieve the output you desire. In answer to your question, "why?", there is logically no difference between your sample file and the SimpleXML output:

  1. XML parsers ignore white space between tags. It doesn't matter if two tags are adjacent (<tag1><tag2/></tag1>) or separated by 57,392,391 empty lines; all the parsers will see are the XML elements.
  2. <game/> is just an XML shorthand for <game></game>. The /> explicitly indicates it is an empty tag.

You are not writing a document within SimpleXML; you are building an XML tree. When you call ->asXML() it writes out the tree in the simplest way possible.

Chris Throup
  • 651
  • 1
  • 4
  • 19