Page 619 - Beginning PHP 5.3
P. 619
Chapter 19: Working with XML
The html after the < !DOCTYPE in the first line signifies that the root element is named html . The
declaration also includes the URI of the DTD on the www.w3.org Web site. If the DTD is an external
document, it can be located anywhere, and identified by any URI that the application reading it
understands and has access to, not just a URL over the Internet.
Specifying Namespaces
An XML namespace indicates the source of names for elements and attributes. Being able to specify the
source of an element or attribute name means that you can use the same name to represent different
things within a single document. An XML document may reference multiple namespaces, if required.
A namespace can be identified within an XML document by referencing it via a special reserved XML
keyword: the xmlns (XML Namespace) attribute. When applied to an element, the namespace is then
valid for that element and its children.
For example, all elements within an XHTML document must be in an XHTML namespace. The simplest
way to do this is to use the xmlns attribute on the root element ( html ) of the XHTML document.
Defining the namespace for the root element also serves to define the namespace for all of its children —
that is, the rest of the elements and attributes in the document:
< html xmlns=”http://www.w3.org/1999/xhtml” >
Creating an XHTML Document
Now that you understand how to create a valid XML document, you can apply this knowledge to create
an XHTML document.
To do this, start by indicating the version of XML you ’ re using, and then provide a DOCTYPE declaration
referencing the XHTML DTD. Next, create the root element — html — and include the xmlns attribute
to declare the XHTML namespace for this element (and all its child elements). Finally, you can include all
the child elements under the html root element — in other words, the content of your XHTML page.
Here ’ s an example:
< ?xml version=”1.0” encoding=”UTF-8”? >
< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
< html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
< head >
< title > An XHTML example < /title >
< /head >
< body >
< p > This is an example of an XHTML Strict document. It can contain images
( < img src=”http://www.example.com/images/image.gif” alt=”an image” / > ) as
well as links ( < a href=”http://example.com/” > example.com < /a > ) and any other
HTML elements, provided they conform to the XML syntax rules. < /p >
< /body >
< /html >
Of course, this document looks very much like an ordinary HTML document, and will be displayed just
like any Web page written in HTML in most browsers. However, unlike an HTML document it conforms
to the XML specification, and is not only well - formed but also valid.
581
9/21/09 9:17:45 AM
c19.indd 581
c19.indd 581 9/21/09 9:17:45 AM