WebReference.com - Part 3 of Chapter 10 from Professional PHP4 XML, from Wrox Press Ltd (1/7) | WebReference

WebReference.com - Part 3 of Chapter 10 from Professional PHP4 XML, from Wrox Press Ltd (1/7)

current pageTo page 2To page 3To page 4To page 5To page 6To page 7
[next]

Professional PHP4 XML, Chapter 10: Putting It Together

Creating Objects from XML Files

[The following is a continuation of our series of excerpts from chapter 10 of the Wrox Press title, Professional PHP4 XML. Source code for the examples discussed can be downloaded at the Wrox Web site (free e-mail registration required).]

This problem is stated as follows - we have an XML document and we want to create PHP objects from the information in the document. These objects can then be used for different tasks depending on the application that needs them. This is known as the XMLable pattern.

Example

We may have an XML file describing books, and we may want to create book objects from our XML document. This is a simplified representation of the XML document:

<?xml version="1.0"?>
<books>
  <book>
    <title>The Two Tours</title>
    <author>J.R.R Tolkien</author>
  </book>
  
  <book>
    <title>Second Foundation</title>
    <author>I.Asimov</author>
  </book>
  
  <book>
    <title>Foundation and Empire</title>
    <author>I.Asimov</author>
  </book>
</books>

And this can be the Book class:

class Book 
{
    var $title;
    var $author;
    function GetTitle() 
    {
        return $this->title;
    }
  
    function GetAuthor() 
    {
        return $this->author;
    }
    function SetTitle($title) 
    {
        $this->title = $title;
    }
    function SetAuthor($author) 
    {
        $this->author = $author;
    }
}

As usual we may think about DOM, XSLT, or SAX, but in this problem we don't have choices, let's see why.

Firstly, DOM is unacceptable in this case. We parse the XML document into the DOM tree, and then we'll be facing the same problem we had before - how to convert the DOM tree to many book objects. XSLT is too exotic for this problem; we may write an XSLT transformation that creates PHP code that creates the objects, and then eval() the transformation result.

So the obvious solution is to use SAX, where we parse the XML document and we create the objects as we collect enough information for each one of them.


current pageTo page 2To page 3To page 4To page 5To page 6To page 7
[next]

Created: August 26, 2002
Revised: August 26, 2002

URL: https://webreference.com/programming/php/php4xml/chap10/3/