05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

document. What if the mail message document has a body element (the subject of the<br />

message), and the attached file is an XML representation of a dissection that also has<br />

a body element, but this element has completely different DTD rules? How can you<br />

possibly validate or make sense of the document if the meaning of body changes partway<br />

through?<br />

This problem is solved with the use of namespaces. Namespaces let you qualify the<br />

XML tag—for example, email:body and human:body.<br />

There’s a lot more to XML than we have time to go into here. For a gentle introduction<br />

to XML, read Learning XML, by Erik Ray (O’Reilly). For a complete reference to<br />

XML syntax and standards, see XML in a Nutshell, by Elliotte Rusty Harold and W.<br />

Scott Means (O’Reilly).<br />

Generating XML<br />

Just as <strong>PHP</strong> can be used to generate dynamic HTML, it can also be used to generate<br />

dynamic XML. You can generate XML for other programs to consume based on<br />

forms, database queries, or anything else you can do in <strong>PHP</strong>. One application for<br />

dynamic XML is Rich Site Summary (RSS), a file format for syndicating news sites.<br />

You can read an article’s information from a database or from HTML files themselves<br />

and emit an XML summary file based on that information.<br />

Generating an XML document from a <strong>PHP</strong> script is simple. Simply change the MIME<br />

type of the document, using the header( ) function, to "text/xml". To emit the declaration without it being interpreted as a malformed <strong>PHP</strong> tag, you’ll need<br />

to either disable short_open_tag in your php.ini file, or simply echo the line from<br />

within <strong>PHP</strong> code:<br />

<br />

Example 11-1 generates an RSS document using <strong>PHP</strong>. An RSS file is an XML document<br />

containing several channel elements, each of which contains some news item<br />

elements. Each news item can have a title, a description, and a link to the article<br />

itself. More properties of an item are supported by RSS than Example 11-1 creates.<br />

Just as there are no special functions for generating HTML from <strong>PHP</strong> (you just echo<br />

it), there are no special functions for generating XML. You just echo it!<br />

Example 11-1. Generating an XML document<br />

<br />

<br />

<br />

<br />

264 | Chapter 11: XML<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!