Page 616 - Beginning PHP 5.3
P. 616
Part III: Using PHP in Practice
❑ Element names may not start with the characters “ xml , “ XML , or any upper - or lowercase
”
”
combination of these characters in this sequence. Names must start with a letter, an underscore,
or a colon, but in practice, you should never use colons unless you ’ re dealing with XML
namespaces. Names are case - sensitive. Letters, numbers, the hyphen, the underscore, and the
period are valid characters to use after the first character
❑ Comments are delimited in the same way as HTML comments ( < ! - - and - - > )
Using XML Elements and Attributes
XML elements and their attributes form the hierarchical structure of an XML document, and contain the
document ’ s data. Although there can be only one root element, every element (including the root) may
contain multiple elements (often referred to as child elements ). In addition, you ’ re allowed to have
multiple child elements all with the same name.
Each XML element may contain one or more attributes; however, an attribute name may appear only
once within any given element.
There is some controversy about when to use an attribute and when to use a child element for containing
data. Although there is no hard and fast rule, a good rule of thumb is:
❑ Use a child element when you might need to include the same field more than once in an
element. For example, the stockList root element described earlier contains multiple item
child elements. It wouldn ’ t be possible to do this with attributes, because you can ’ t have more
than one attribute with the same name for any given element
❑ Use an attribute when you ’ re sure the data will occur only once within the element, such as the
type attribute for the item elements (an item can be a fruit or a vegetable, but not both)
Another good rule of thumb is: use child elements for data that is core to the element, and use attributes
for data that is peripheral to the element, or that uniquely identifies an element (such as an id attribute) .
Valid XML Documents: DTDs and XSDs
As explained earlier, a valid XML document is one that contains a reference to a DTD (document type
definition) or an XSD (XML Schema definition), and whose contents follow both the general XML syntax
rules (meaning it is well - formed), and also the rules specified in the DTD or XSD (which means it is
valid). The “ stock list ” XML document described earlier is both well - formed and (potentially) valid:
< ?xml version=”1.0” encoding=”UTF-8”? >
< !DOCTYPE stockList SYSTEM “http://www.example.com/dtds/stockList.dtd” >
< stockList >
< item type=”fruit” >
< name > apple < /name >
< unitPrice > 0.99 < /unitPrice >
< quantity > 412 < /quantity >
< description > < ![CDATA[Apples are > > > yummy < < < ]] > < /description >
< /item >
< item type=”vegetable” >
< name > beetroot < /name >
< unitPrice > 1.39 < /unitPrice >
578
9/21/09 9:17:44 AM
c19.indd 578 9/21/09 9:17:44 AM
c19.indd 578