Serving XML

In the previous section, "The "Hello World" of Ajax and PHP," data was served up as plain text. This is great when no post-processing is necessary. However, most applications require the data to be displayed a specific way. You could answer the request with formatted HTML instead of plain text, but then the web application is limited in how it can use the data. We want to separate data and display functionality. Instead, we use markup and data encoding to transmit the data in a format that both PHP and JavaScript can understand without dictating how it should be displayed. The first such format, and arguably the most common, is XML.

We will tackle the XML problem on two fronts: the server using PHP and the consumer (client) using JavaScript. We take on the server first. But before we do anything, we need to agree on a format for our data.

Designing an XML File

XML is a markup language that can be used to encapsulate any type of data that is transmitted over the network or stored on a disk. By definition, the format is generic (extensible) and does not automatically indicate the type of data that it contains. We have to create the format. In this sense XML is a self-descriptive language.

The document always starts with a directive telling the XML parser that the file is indeed XML. The directive also tells the parser the version and optionally the encoding type of the data. Encoding type is the format in which each character in the file is stored.

XML documents always consist ...

Get Ajax with PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.