-
Continue Reading »
PHP and XML Using SimpleXML

XML is a very nice tool for creating configurations, simple 'databases' and other parts of web applications that don't require a full-fledged data source. There are many ways to work with XML in PHP, and in this tutorial I will cover using SimpleXML and working with the data as (essentially) an array object and file.Download Demo
If you're more of a trial-by-fire learner, simply download the demo and play around with it on your own server. If you need an explanation of any of the moving parts, just flip back to this page. Just be sure to give 'write' permissions to the example.xml file before you start...
XML Structure
For this example I'm simply creating an XML file to store user information, stuff that COULD be used for checking login credentials, etc.
<?xml version="1.0" encoding="utf-8"?> <users> <user> <uid>1</uid> <name>John Doe</name> <password>1hskckei</password> <email>john@johndoe.com</email> </user> </users> Step 1 : Reading an XML File and Generating Output
First I like to define the file separately, this allows me to maintain the file source in one location and call it if I need to reload the file (for example; after rewriting the file on modification):
$xml_file = "example.xml";
This is the easy part, simply use the following code to load the XML file into the $xml variable:
if(!$xml=simplexml_load_file($xml_file)){ trigger_error('Error reading XML file',E_USER_ERROR); }Next, you may want to output this data, to do so simply loop through the values in the $xml object just like you would do with an array:
foreach($xml as $user){ echo 'Name: '.$user->name.', Password: '.$user->password.', Email: '.$user->email.' <a href="?rem=' . $user->uid . '">(remove)</a><br /><hr />'; }
Step 2 : Writing to an XML File
Let's start with something easy. SimpleXML gives us the addChild() method which allows you to easily add a node. Basically what I've done here is pulled in the contents of a submitted form, created an ID based on incrementing the last node's uid value and appended it to the file:
$u_name = stripslashes($_POST['u_name']); $u_password = stripslashes($_POST['u_password']); $u_email = stripslashes($_POST['u_email']); // Generate new (appended) ID foreach($xml as $user){ $last_id = $user->uid; } $id = $last_id+1; // Add node $x = $xml->addChild("user"); $x->addChild("uid",$id); $x->addChild("name",$u_name); $x->addChild("password",$u_password); $x->addChild("email",$u_email); $xml->asXML($xml_file);Step 3 : Modifying a Record
To modify a record we simply loop through the contents of the $xml object and modify if the record is a match, all the while rebuilding the XML file and then outputting that file to it's original source. The $mod variable contains the
of the element I want to modify - while looping through the array if the value is found it updates the node: $mod = $_POST['u_record']; $u_password = $_POST['u_password']; $xml_rebuild = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<users>\n"; foreach($xml as $user){ if($user->uid!=$mod){ $xml_rebuild .= "<user>\n <uid>" . $user->uid . "</uid>\n <name>" . $user->name . "</name>\n <password>" . $user->password . "</password>\n <email>" . $user->email . "</email>\n </user>\n"; } else{ $xml_rebuild .= "<user>\n <uid>" . $user->uid . "</uid>\n <name>" . $user->name . "</name>\n <password>" . $u_password . "</password>\n <email>" . $user->email . "</email>\n </user>\n"; } } $xml_rebuild .= "</users>"; $fh = fopen($xml_file, 'w') or die("can't open file"); fwrite($fh, $xml_rebuild); fclose($fh); // Reopen the new XML file if(!$xml=simplexml_load_file($xml_file)){ trigger_error('Error reading XML file',E_USER_ERROR); }Step 4 : Deleting a Record
Very similar to modifying a record, to delete a record you loop through the $xml object and rebuild the results (skipping over the node you want to delete):
$rem = $_GET['rem']; $xml_rebuild = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<users>\n"; foreach($xml as $user){ if($user->uid!=$rem){ $xml_rebuild .= "<user>\n <uid>" . $user->id . "</uid>\n <name>" . $user->name . "</name>\n <password>" . $user->password . "</password>\n <email>" . $user->email . "</email>\n </user>\n"; } } $xml_rebuild .= "</users>"; $fh = fopen($xml_file, 'w') or die("can't open file"); fwrite($fh, $xml_rebuild); fclose($fh); // Reopen the new XML file if(!$xml=simplexml_load_file($xml_file)){ trigger_error('Error reading XML file',E_USER_ERROR); }CDATA
The methods above show a very simple method of working with pure-text XML file contents. If you end up working with contents that use HTML markup or other code then it is imparitive you tell the XML to ignore this content and not treat it like child nodes. This can be done with the CDATA call. For example, say I wanted to include a node for notes on each user that was generated from a WYSIWYG editor and included HTML markup:
<![CDATA[ SPECIAL_FORMAT_STRING ]]>
Conclusion
The above is a very simple example of working with XML in PHP using the built-in SimpleXML module. This isn't a end-all guide to working with XML, there is a lot more that can be done with this powerful tool, but this is how I got started (I found all this stuff in separate locations and peiced it together). Hopefully it saves you the hassel of digging around the interwebs trying to figure out how to do some simple work with XML.
-
2/1/10 at 12:11 pm
It's been awhile
So, I've been out of the loop the past several weeks with a move to La Crosse, WI and all the insanity that follows migrating a family of 3 (+1 brother-in-law) 500 miles. I have been getting into some new stuff though, and here's my starter list for new things of 2010.Continue Reading »
-
12/23/09 at 2:23 pm
jQuery Quotes Slider
I built this some time ago for a client, but it never got used on the site. Always loved it and wanted to put it out there for everyone. Enjoy!Continue Reading »
Latest Tweet
More Coming...
If you can't tell, I just rebuilt my website, new (custom) CMS and all.
Problem is I need more content. Hoping to have this area populated quickly.