Generating XML
Just as PHP can be used to generate dynamic HTML, it can also be used to generate dynamic XML. You can generate XML for other programs to make use of based on forms, database queries, or anything else you can do in PHP. One application for dynamic XML is Rich Site Summary (RSS), a file format for syndicating news sites. You can read an article’s information from a database or from HTML files and emit an XML summary file based on that information.
Generating an XML document from a PHP script is simple. Simply change
the MIME type of the document, using the header()
function, to "text/xml"
. To emit the <?xml ... ?>
declaration without it
being interpreted as a malformed PHP tag, simply echo
the line from within PHP code:
echo
'<?xml version="1.0" encoding="ISO-8859-1" ?>'
;
Example 11-1 generates an RSS
document using PHP. An RSS file is an XML document containing several
channel
elements, each of which
contains some news item
elements. Each
news item
can have a title, a
description, and a link to the article itself. More properties of an
item
are supported by RSS than Example 11-1 creates. Just as there are no
special functions for generating HTML from PHP, there are no special
functions for generating XML. You just echo
it!
Example 11-1. Generating an XML document
<?
php
header
(
'Content-Type: text/xml'
);
echo
"xml version=
\"
1.0
\"
encoding=\'ISO-8859-1
\"
?>"
;
?>
<!DOCTYPE rss PUBLIC '-//Netscape Communications//DTD RSS 0.91//EN"
"http://my.netscape.com/publish/formats/rss-0.91.dtd"> ...
Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.