Wednesday, January 4, 2012

Create an XML File in PHP

One of the things you may find yourself needing to do in your PHP Development, is to create an XML file for one reason or another.  Creating an XML file is useful for a variety of things, and I've found it useful in situations where I use SPRY (JavaScript) to create an interactive environment for the end user.

When I first started researching this, I didn't quite understand the benefit of creating an XML file.  I was under the false assumption that this file had to be static, and couldn't figure out why you would ever create this file other then for static code tables.  I was quite delighted that I was able to create a dynamic XML file, meaning I could create this on the fly from any PHP screen without having to have previously stored it. 

Here's an example of how I use this in one of my applications, and the code used to generate the XML file.

Requirement

Create a Master/Detail region on a page that allows a user to click on an entry in a "master region" on the left side of the screen, and populate a "detail region" on the right side of the screen.  All of this should happen in real time, without having to re-send the page to the server and without having to re-populate the screen.



Solution

As part of the initial page creation and after the normal PHP processing that is required, I created a SPRY data set based upon an XML file.  This is where the beauty of the solution comes into play.  The XML file is created right at the moment of creating the SPRY data set, and is based upon the data in the query that you write.  So in reality, you are creating a temporary XML file based upon the data in your database at that moment in time.  Once I've created that SPRY data set, I'm then free to use it on the client as part of my Master/Detail region.



This above code creates a SPRY data set called dsAdvisor, by executing the xml-advisor-list.php file which creates the XML file. 

Now for the XML:




This code loops through each record returned in the rsAdvisorList record set, and creates an XML file using the database column names as the tags.

That's all there is to it.  You can run this file that creates the XML script and when it opens in your browser window simply do a Save As to save it off as an XML file.

No comments:

Post a Comment

Popular Posts