Lets talk about XML. XML strands for Extensible Markup Language. It's just like HTML, it has tags, however those tags are not predefined, you can make up any tag you wish. XML is used to store data, although you could use HTML for it, it'd be really hard to organize, manage and describe data using HTML tags.
Here's how a simple XML document look like.
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body> Don't forget me this weekend! </body>
</note>
Basic XML structure.
1. XML version declaration.
2. Root element, opening/closing. Also called parent.
3. Child elements and siblings..
So it's,
VERSION DECLARATION
<root opening>
<child opening1> content </child closing1>
<child opening2> content</child closing2>
<more child opening> more content </more child closing>
<\root closing>
Know that all our structure goes inside the root elements and you cannot have more than one root element on a page.
Before we move any further, lemme tell you guys what parent, child and sibling is. We have child that's nested within parent element.
<parent>
<child>Text</child>
</parent>
Here <root> is parent of <paragraph> and <paragraph> is parent to <sentence>. <sentence> is child of <paragraph>. And those two <sentence> are sibling to each other.
<root>
<paragraph>
<sentence>This is a sentence</sentence>
<sentence>This is another sentence</sentence>
</paragraph>
</root>
These elements can also have attributes. Attributes provide additional information. Example below we've a <person> which is a parent element, with attribute gender and its value is 'female'.
<person gender="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
We've covered the basics, now here's the fun part. You can fetch those information, or allow others to do it, different languages provide different extensions, in PHP we've SimpleXML parser. It allows you to get element name, attributes, text nodes etc..
For example, code below will return an object representation of languages.xml file, you can then iterate through it and display appropriate information,
$languages = simplexml_load_file("languages.xml");
Another practical example would be to load a website that provides content in XML format using file_get_contents() function and use simplexml_load_string() to then loop and get specific data. You then could even post that data on your site if allowed.
No comments:
Post a Comment