Returning XML with PHP

Some times (when working with Ajax requests or serving data for other sites) we need to generate XML output.

Sending the well formed XML code only will not be interpreted as XML or will be very hard to parse. For external applications and Ajax will be available as simple text.

In order to serve it as XML we need to set the MIME type as such.

The proper MIME type is text/xml.

For the format to be available and the client application (browser, Javascript functions, external web pages) to be able to interpret our output as XML, we will have to change the content type in the response header:

// set proper header
header("Content-type: text/xml");

Just remember one thing: Always change response header information BEFORE sending any output (echoprint and anything else which has the ability to generate any kind of output).

After we set the content type, we will need to assemble the XML which will be later parsed by the client application.

The first element of the response must be an XML declaration:

<?xml version="1.0" encoding="[suitable for the content language - usually utf-8 will be OK]" ?>
<!-- xml prolog -->

Without this, the content of the XML response will not be parsed, or even worst, the XML parser will throw an error.

After that, we will create the XML structure, wich will hold the data.

There are many ways to create XML output such as follows:

  • creating as text, line by line: This is a quick and dirty method, but prone to DOM errors, such as missing closing tags, overlapping elements, and is very hard to debug, especially when we are working with large amounts of different data types. Further processing (such as sorting, injecting new elements into the DOM tree, removing elements, changing properties) will be far more difficult, if not impossible.
  • generating XML with different XML libraries (bundled with PHP, or classes created for this): Personally, i recommend, to use this method, as it will generate the full XML document (with the aforementioned XML declaration), and you will certainly avoid the errors often encountered with the text generation method. Also, XML documents created with this method can be easily transferred to other plugins, functions and classes, and further processing will be easy, as you will work with DOM elements. Processing XML in the DOM way leads to infinite possibilities.

Filling up XML with data and XML processing will be the subject of another article.

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.