1

I'm generating some XML data in response to an HTTP POST request. I'm setting the MIME

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

and everything is working well so far.

I'm generating the xml response as follows:

 $response = '<?xml version="1.0" encoding="utf-8"?>';
 $response .= '<error>';
 $response .= '<description>'.$error.'</description>';
 $response .= '</error>';
 echo $response;

I would now like the format the XML so that instead of seeing this response:

<?xml version="1.0" encoding="utf-8"?><error><description>Login Error: No Username Supplied</description></error>

they see this response:

<?xml version="1.0" encoding="utf-8"?>
 <error>
    <description>Login Error: No Username Supplied</description>
 </error>

I haven't worked with XML output with PHP before so not sure if there's a built in method for doing a "pretty print" type function on the output?

user982124
  • 4,416
  • 16
  • 65
  • 140
  • How are you outputting the XML? Take a look at this thread, http://stackoverflow.com/questions/8615422/php-xml-how-to-output-nice-format. – chris85 Nov 02 '15 at 04:13
  • 1
    slightly offtopic: "format the XML correctly" - neither version is more correct than the other per se. You probably mean "more human-readable". And then the document definition must allow that (i.e. white-spaces can be skipped). – VolkerK Nov 02 '15 at 04:45

1 Answers1

0

Use the DOM library and set the formatOutput property to true

$doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true;

$root = $doc->createElement('error');
$doc->appendChild($root);

$desc = $doc->createElement('description', $error);
$root->appendChild($desc);

echo $doc->saveXML();

Demo ~ https://eval.in/461384

Phil
  • 157,677
  • 23
  • 242
  • 245