9

I am using following code to get an XML file when a php page is called:

i.e. when you enter http://example.com/strtoxmp.php, it will return you xml, based on following coding:

  $xml = new SimpleXMLElement("<feed/>");

  $feed = $xml;
  $feed->addChild('resultLength', "1");
  $feed->addChild('endIndex', "1");

  $item = $feed->addChild('item',"");
  $item->addChild('contentId', "10031");
  $item->addChild('contentType', "Talk");
  $item->addChild('synopsis', "$newTitle" );
  $item->addChild('runtime', ' ');
}

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

print($xml->asXML());

and it is working fine. It produces following xml:

<?xml version="1.0"?>
<feed>
<resultLength>1</resultLength>
<endIndex>1</endIndex>
<contentId>10031</contentId>
<contentType>Talk</contentType>
<synopsis>Mark Harris - Find Your Wings</synopsis>
<runtime> </runtime>
</item>
</feed>

But I need

< ?xml version="1.0" encoding="UTF-8" standalone="yes"?>

instead of

< ?xml version="1.0"?>

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
SJSSoft
  • 723
  • 2
  • 10
  • 28

1 Answers1

29

To set the XML declaration, just add it to the string you pass to the SimpleXMLElement constructor:

$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" '
  . 'standalone="yes"?><feed/>');

This should output the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed/>
Ben
  • 1,902
  • 17
  • 17
  • Thanks, I worked. I was shocked at the results. Can you please explain it, how it happened. Technically, what I was missing.I have tried `` but shown error. – SJSSoft May 05 '13 at 17:31
  • Did you also add a root element when you passed that string to the constructor? If not, you wouldn't have had a valid XML document... – Ben May 05 '13 at 22:18
  • Just in case someone is looking for that one: If you also want to add style declarations: add something like `` just before your `` object. (or css style if you prefer) – Hafenkranich May 12 '16 at 18:51