Pretty print XML in PHP

As part of my freelance work I send data to APIs, often using XML for data transfer. I log the XML sent and received for debugging and auditing, however the XML often has no line breaks or indentation, making it difficult to read.

Fortunately there’s a simple way to pretty print or format XML strings in PHP, by using the DOMDocument class with a few parameters. I’ve used a hardcoded XML string in the example below, but if you have a SimpleXmlElement object the asXML function will return the XML as a string.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$xml = '<test><a><b></b></a><c></c></test>';
$dom = new \DOMDocument('1.0');
$dom->preserveWhiteSpace = true;
$dom->formatOutput = true;
$dom->loadXML($xml);
$xml_pretty = $dom->saveXML();
<?php $xml = '<test><a><b></b></a><c></c></test>'; $dom = new \DOMDocument('1.0'); $dom->preserveWhiteSpace = true; $dom->formatOutput = true; $dom->loadXML($xml); $xml_pretty = $dom->saveXML();
<?php

$xml = '<test><a><b></b></a><c></c></test>';
$dom = new \DOMDocument('1.0');
$dom->preserveWhiteSpace = true;
$dom->formatOutput = true;
$dom->loadXML($xml);
$xml_pretty = $dom->saveXML();

The output of running the above code is:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?xml version="1.0"?>
<test>
<a>
<b/>
</a>
<c/>
</test>
<?xml version="1.0"?> <test> <a> <b/> </a> <c/> </test>
<?xml version="1.0"?>
<test>
  <a>
    <b/>
  </a>
  <c/>
</test>

2 Comments

  1. Yatin Mistry

    It worked. Thanks man

  2. Ricardo Uhalde

    Thanks a lot Paul, worked perfectly! Just my two cents, you should set preserveWhiteSpace to false, when your XML lacks of CR and LF. My XML text had no \r\n and your code didn’t work on first try.

Comments are closed