XML and PHP Simplified / Page 2 | WebReference

XML and PHP Simplified / Page 2


[prev]

XML and PHP Simplified [con't]

xml_get_error_code: Gets XML parser error code (defined as constants, such as XML_ERROR_NONE and XML_ERROR_SYNTAX). Use xml_error_string to get the textual description of the error based on the error code. Sample use of this function:



Result of this code:


xml_set_option: There are several options that can be set for an xml parser:
XML_OPTION_CASE_FOLDING and XML_OPTION_TARGET_ENCODING. The case folding option is enabled by default, and means that element names will be made uppercase unless it is disabled. Target encoding enables you to specify which encoding is used for the target; the default is the encoding used by xml_parser_create, which in turn is ISO-8859-1. Use xml_parser_get_option to find out what options are currently set for an xml parser.

Result of the code:

Option code is:0

Let's create an XML document. The first step is to actually create the xml file first. To do this we will use PHP's file functions; we don't need PHP XML functions for this. Then we create the tags and attributes. We want our document to look something like this:

We will set the xml version to one. So create a new PHP document and add the following code:

When you run the code it produces something like this:

Figure 1

The XML document viewed in Internet explorer:

Figure 2

The small program here does two things, first it creates the XML file and then it adds the content that you want. The HTML part of the form simply presents a form to collect the information. Below is an explanation of the PHP code. First we check if the form has been submitted:

Now we need to make sure that all fields have been filled in, otherwise there would be no point in running the program in the first place. We use the empty() function to see if the form variables have been filled in:

If the error message variable is not filled in, in other words if no errors occurred during the validation process, we continue to build the xml document:

if(empty($msg)){

First we create the file:

Then we open it for writing:

Then we simply close it again:

//close the file
fclose($fp);

Then we inform the user of the outcome:

This program automates the creation of an XML document and gives some flexibility as to what kind of elements and tags you can add. You can further develop it to suit your needs. For instance, if you run a blog site, you can add the latest topics to an XML document and make it available as an RSS file for interested readers to download or to attract bloggers to your site. In the next article, we will focus how to merge information retrieved from a database into an XML document.

Original: June 25, 2009


[prev]