Jump to content

Archive:PHP and MySQL Programming/XML and PHP

From IdeaWazaWiki
Revision as of 09:47, 4 April 2006 by wikademia>Ralfe
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

TOC


Introduction

XML (eXtensible Markup Language) is used in mainstream development. It might have started off as an attempt at a web standard, but is now used even in more traditional applications as a document standard. For example, the Open Document Format employed by Sun in their StarOffice and OpenOffice suites is based on XML.

Because of its wide-spread use in the IT industry, it is fitting that we as PHP developers know how to make use of XML files in our PHP applications.

XML Structure

Since XML documents are extensible, there are no limits to the tags that you can create to define data with. Here is an example of a simple XML document :

<?xml version="1.0"?>
<document>
   <title>Isn't this simple!</title>
   <body>XML is as simple as pie. :-)</body>
</document>

The reason that it looks so simple, is because it is so simple! Just as in HTML, elements are enclosed by angled brackets : "<" and ">", where the start element differs from the end element by the exclusion of a forward slash : "/".

Creating an XML Parser in PHP

Defining the XML Parser

In PHP, you define an XML Parser by using the xml_parser_create() function as shown below.

<?
$parser = xml_parser_create(ENCODING);
?>

You can think of the $parser variable in terms of a file handler for the XML document. Note that the ENCODING can be either 1. ISO-8859-1 (default) 1. US-ASCII 1. UTF-8

Defining the Element Handlers

Element handlers are defined by means of the xml_set_element_handler() function as follows :

<?
xml_set_element_handler(XML_PARSER, START_FUNCTION, END_FUNCTION);
?>

The three arguments accepted by the xml_set_element_handler() function are :

1. XML_PARSER - The variable that you created when you called the xml_parser_create() function. 2. START_FUNCTION - The name of the function to call when the parser encounters a start element. 3. END_FUNCTION - The name of the function to call when the parser encounters an end element.

e.g. :

<?
$parser = xml_parser_create();
xml_set_element_handler($parser, "startElement", "endElement");
?>


Defining Character Handlers

Starting the Parser

Cleaning Up

Example

<?
# --- Element Functions ---

function startElement($parser, $name, $attributes){
   # ... some code
}

function endElement ($parser, $name){
   # ... some code
}

# --- Main Program Body ---
$parser = xml_parser_create();
xml_set_element_handler($parser, "startElement", "endElement");
?>

Parsing XML Documents

Dumping Database Contents into an XML File