Modifying XML
Having a repository of information is important; updating it frequently after additions and deletions is even more so. This applies not only to repositories like databases, but also configuration data and structured information units that are maintained as XML documents. For server-side updates of information, PHP provides an API to do the same for XML documents. A real-world example that follows will help in getting a good idea of this concept.
Consider the following scenario: every day a few thousand babies are born in the USA. Since babies born in this country are automatically citizens by birth, a lot of information (birth certificates, Social Security information etc.) needs to be created and maintained at several levels, starting with the database in the city of birth. The records for babies born in NYC, for example, are created on a daily basis. One such document would look like:
<?xml version="1.0" encoding="UTF-8" ?>
<daily-births city="NYC" date="11-29-2012">
<baby>
<time>00:00:12</time>
<name>Sandy</name>
<sex>F</sex>
</baby>
<baby>
<time>00:00:21</time>
<name>Chris</name>
<sex>M</sex>
</baby>
...
</daily-births>
Now suppose that new entries need to be added to this XML document whenever a new baby is born. We could write a PHP script to do just that!
<? $xml = simplexml_load_file("newborns.xml");
$baby = $xml->addChild('baby');
$time = $baby->addChild('time', "00:00:12");
$name = $baby->addChild('name', "Cindy");
$sex = $baby->addChild('sex', "F");
echo $xml->asXML();
?>
The above piece of code is very intuitive and simple to visualize. Note that we have indented the code statements so that it resembles the nesting of elements in the XML document that we are accessing. Kind of makes it more readable, don't you think?
It is also possible to update current information with new values for element attributes and content. For example, suppose that after a baby named Sandy was born, her parents decided to rename her (as the father insisted she be named after his mother!) Suppose they decided to call her Heloise. PHP code to perform this update would look like:
<?
$xml = simplexml_load_file("newborns.xml");
$xml->baby[2]->name = "Heloise";
echo $xml->asXML();
?>
Voila! It's really simple, isn't it? PHP code is very readable, so don't be surprised if you feel at home immediately. With this video, we come to the end of this course on the XML standard, manipulating XML documents and processing them in server- and client-side applications. Hope you had a good time; we definitely did!