Next freebie in 28 Hours*
We saw in the previous summary. that while we can directly output XML document data that is simply organized as a root element with content (and no nested elements within,) we aren't lucky enough to get such simply structured documents in everyday software tasks or projects. PHP language implementations provides syntactic constructs to work around the problem we saw previously; namely that elements with other nested elements draw a total blank when an attempt is made to render them.
There are two main constructs provided:
Probably a live example would clarify the above statements. Consider an XML document that has the following information stored: a description of the chassis of an automobile. For example:
<?xml version="1.0" encoding="UTF-8" ?>
<battery model="amaron" power="500W"/>
<engine model="VW1200" capacity="1200cc" hp="100"/>
The PHP code sample given below explains how to extract all the information regarding the model name and engine specification of a car manufactured by a German automobile giant. Please read carefully... the syntax is very simple and intuitive... just try to visualize a tree structure:
$xml = simple_xml_load_file("auto.xml");
The output will be the value of the model element and the attribute value of model inside the engine element. A complication arises if the tag name of an XML element has the character '-' as part of the label. For example, if the attribute "model" of the element "automobile" were to be renamed as "engine-model", then the statement to extract the model attribute would be changed. The name should be enclosed in double quotes, as in "engine-model"; unlike the other scenario, where we could use the attribute name un-quoted.
So we can now handle both trivial as well as non-trivial XML document formats in PHP. Handling means loading, opening, parsing and processing. There are other useful APIs for handling XML documents in the language, which we'll encounter in the following videos.
Have a question but don't want to ask it publicly? If you are a prime member just ask right here and we will get back to you within 48 hours. Not prime yet? no worries you can ask publicly below.