This post covers the XML Basics section of the Data Formats and Types chapter when studying for the Zend PHP 7 Certification.
XML stands for Extensible Markup Language, and it is used to store or transport data.
An example of how an XML document might look can be seen below.
<?xml version="1.0"?> <productListing title="Product Listing"> <product> <name>Product One</name> <description>Some description about Product One.</description> <cost>£19.95</cost> <shipping>£2.95</shipping> </product> <product> <name>Product Two</name> </product> </productListing>
XML documents should start with the encoding declaration that identifies which encoding is used to represent the characters in the document.
Although an XML declaration is not required in all XML documents, XHTML document authors are strongly encouraged to use XML declarations in all their documents.
XML documents can contain international characters, like Norwegian øæå or French êèé. To avoid errors, you should specify the encoding used, or save your XML files as UTF-8.
The simplest XML elements contain an opening tag, a closing tag, and some content. The opening tag begins with a left angle bracket,
<, followed by an element name that contains letters and numbers (but no spaces), and finishes with a right angle bracket,
Note that the name of the opening tag you use must be the same name used for the closing tag, else the XML document will not be valid.
As well as opening and closing tags, you can also have empty element tags which self-close, and can written like the below.
Within XML, elements can have attributes similar to attributes in HTML. Within an XML document these attributes must be quoted.
<someElement value=4>Some Description</someElement> <!-- Incorrect --> <someElement value="4">Some Description</someElement> <!-- Correct -->
There are also some characters that should be escaped within XML. For example, you may have a node that looks like this:
<apple> <notes>Price < 10</notes> </apple>
< tag used between the pair of “notes” tag is the same character used for the opening tags, therefore it needs to be escaped to form a valid XML document. A list of other characters that should be escaped can be seen below:
View the other sections:
Note: This article is based on PHP version 7.0.