1

When I use $start var like this:

$start = "<?xml version='1.0' encoding='utf-8'?/>";

I get a fatal error:

Fatal error: Uncaught Exception: String could not be parsed as XML in /home/users/....../test.php:6 Stack trace: #0 /home/users/....../test.php(6): SimpleXMLElement->__construct('<?xml version='...') #1 {main} thrown in /home/users/....../test.php on line 6

How can I generate nice formatted XML tag for XML?

$start = "<xml version='1.0' encoding='utf-8' />";
//$start = "<?xml version='1.0' encoding='utf-8'?/>";

$gmXML = new SimpleXMLElement($start);
$offers = $gmXML->addChild('offers');

Header('Content-type: text/xml;');

echo $gmXML->asXML();

What I need is:

<?xml version='1.0' encoding='utf-8'?>
showdev
  • 28,454
  • 37
  • 55
  • 73
user3245716
  • 33
  • 1
  • 6
  • i think you're getting confused about ` – Kevin Jul 17 '19 at 06:51
  • See [Modify XML prolog in PHP](https://stackoverflow.com/questions/35376444/modify-xml-prolog-in-php) and the comments [here](https://stackoverflow.com/a/16386530/924299) about adding a root element. – showdev Jul 17 '19 at 06:53
  • Thank you guys. As Ghost wrote and I was confused about declaration and tag. Thanks for a link also! – user3245716 Jul 17 '19 at 07:07

1 Answers1

3

The problem is that <?xml version='1.0' encoding='utf-8'?/> (although with a slight mistake in it anyway) doesn't actually define an XML element as it has no root node.

With your current code, you would have to add the <offers> element to the XML to give it the actual element content...

$start = "<?xml version='1.0' encoding='utf-8'?><offers />";

$gmXML = new SimpleXMLElement($start);

Header('Content-type: text/xml;');

echo $gmXML->asXML();

Also note the end of the definition is ?> and not ?/>

As your other version of the XML...

$start = "<xml version='1.0' encoding='utf-8' />";

This actually declares a root node called <xml>.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • In case anyone thinks the `` form might be useful in some way, it's worth noting that `xml` and anything beginning `xml` is a reserved name in the XML spec, so should never be used. – IMSoP Jul 18 '19 at 16:45