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.

<?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:

<?xml version="1.0"?>
<test>
  <a>
    <b/>
  </a>
  <c/>
</test>

2 Comments

  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.