Miscellaneous Code
  Home arrow Miscellaneous Code arrow Objects to XML Serializer/Unserializer
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
MISCELLANEOUS CODE

Objects to XML Serializer/Unserializer
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2006-03-22

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    [PHP5]
    This package is used to serialize objects to xml, or unserialized xml to objects.
    The properties of the object MUST be public (right now...later, we will see :-) )
    The way to use it is quite simple, and the index.php page shows an exemple.

    $oObj = new object;
    // here, I modify the properties of my object.

    $oxml = new xmlserialize ($oObj);
    $oxml -> getProps ();
    // here, I get the PUBLIC properties of the object
    $sXml = $oxml -> xmlToVars ();
    // here, I get an xml string of my serialized object!
    // I can save it to a file...
    $oNewObj = $oxml -> xmlToVars ($sXml);
    // Here, I unserialized my object with the xml string (can be done later of course!).

    Updated : I set a new method : __toString. It must be used by echoing the object (if your object's name is $oxml, just write : echo $oxml;).
    This is a first version, as the display is a bit buggy.
    Well, first, if the xml has been generated, it will display this xml. This feature uses the XSLTProcessor extension (must be set in your php.ini).
    If it has not been generated, it will display an export of the properties that can be serialized.

    UPDATE : the XML display is now perfect, thanks to a new XSL.

    By : malalam

    <?php
    /**
    * CLASS xmlSerializer
    * object to xml serialization and unserialization
    * @auteur : johan <barbier_johan@hotmail.com>
    * @version : 1
    * @date : 2006/03/22
    *
    * free to use, modify, please just tell me if you make any changes :-)
    */
    class xmlserialize {

    /**
    * private object oObj
    * the object we work on
    */
    private $oObj = null;
    /**
    * private array of object oPropObj
    * objects needed by the main object, because some of its properties are objects
    */
    private $oPropObj = array ();
    /**
    * private array aProps
    * the PUBLIC properties of the object
    */
    private $aProps = array ();
    /**
    * private string xml
    * the xml serailization of the object
    */
    private $xml = '';
    /**
    * public string node
    * a fragment of the xml string
    */
    public $node = '';

    /**
    * public function __construct
    * constructor
    * @Param (object) $obj : the object we want to serialize/unserialize
    * @Param (array) $oPropObj : array of objects needed by the main object
    */
    public function __construct ($obj, array $oPropObj = array ()) {
    if (!is_object ($obj)) {
    trigger_error ('The first argument given is not an object', E_USER_ERROR);
    } else {
    $this -> oObj = $obj;
    }
    if (!empty ($oPropObj)) {
    foreach ($oPropObj as $clef => $oVal) {
    if (is_object ($oVal)) {
    $this -> oPropObj[$clef]['object'] = $oVal;
    $this -> oPropObj[$clef]['class'] = get_class ($oVal);
    }
    }
    }
    }

    /**
    * public function getProps ()
    * method used to get the public properties of the object
    */
    public function getProps () {
    $this -> aProps = get_object_vars ($this -> oObj);
    }

    /**
    * private function recVarsToXml
    * method used to serialize the object, recursive
    * @Params (DomDocument) & docXml : the DomDocument object
    * @Params (DomElement) & xml : the current DomElement object
    * @Params (array) & aProps : the array of properties we work on recursively
    */
    private function recVarsToXml (& $docXml, & $xml, & $aProps) {
    foreach ($aProps as $clef => $val) {
    if (empty ($clef) || is_numeric ($clef)) {
    $clef = '_'.$clef;
    }
    $domClef = $docXml -> createElement ((string)$clef);
    $domClef = $xml -> appendChild ($domClef);
    if (is_scalar ($val)) {
    $valClef = $docXml -> createTextNode ((string)$val);
    $valClef = $domClef -> appendChild ($valClef);
    } else {
    if (is_array ($val)) {
    $this -> recVarsToXml ($docXml, $domClef, $val);
    }
    if (is_object ($val)) {
    $oXmlSerialize = new self ($val);
    $oXmlSerialize -> getProps ();
    $oXmlSerialize -> varsToXml ();
    $objClef = $docXml -> importNode ($oXmlSerialize -> node, true);
    $objClef = $domClef -> appendChild ($objClef);
    }
    }
    }
    }

    /**
    * public function varsToXml
    * method used to serialize the object
    * @Return (string) $xml : the xml string of the serialized object
    */
    public function varsToXml () {
    $docXml = new DOMDocument ('1.0', 'utf-8');
    $xml = $docXml -> createElement ('object_'.get_class ($this -> oObj));
    $xml = $docXml -> appendChild ($xml);
    $this -> recVarsToXml ($docXml, $xml, $this -> aProps);
    $this -> node = $xml;
    return $this -> xml = $docXml -> saveXML ();
    }

    /**
    * private function recXmlToVars
    * method used to unserialize the object, recursive
    * @Param (array) aProps : the array we work on recursively
    */
    private function recXmlToVars ($aProps) {
    foreach ($aProps as $clef => $val) {
    $cpt = count ($val);
    if ($cpt > 0) {
    foreach ($val as $k => $v) {
    $cpt2 = count ($v);
    if ($cpt2 > 0) {
    if (substr ($k, 0, 7) === 'object_') {
    foreach ($this -> oPropObj as $kObj => $vObj) {
    if ($this -> oPropObj[$kObj]['class'] === substr ($k, 7)) {
    $oXmlSerializer = new self ($this -> oPropObj[$kObj]['object']);
    $oXmlSerializer -> getProps ();
    $sXml = $oXmlSerializer -> varsToXml ();
    $oXmlSerializer -> xmlToVars ($sXml);
    $this -> oObj -> {$clef}[substr ($k, 7)] = $oXmlSerializer -> getObj ();
    }
    }
    } else {
    $this -> recXmlToVars ($v);
    }
    } else {
    if ($k{0} === '_') {
    $k = substr ($k, 1, strlen($k) - 1);
    }
    $this -> oObj -> {$clef}[$k] = current ($v);
    }
    }
    } elseif (!empty ($val)) {
    $this -> oObj -> $clef = current ($val);
    }
    }
    }

    /**
    * public function xmlToVars
    * method used to unserialize the object
    * @Param (string) xml : optional xml string (an already serialized object)
    */
    public function xmlToVars ($xml = '') {
    if (empty ($xml)) {
    $xml = simplexml_load_string ($this -> xml);
    } else {
    $xml = simplexml_load_string ($xml);
    }
    $this -> recXmlToVars ($xml);
    }

    /**
    * public function getObj
    * method used to get the unserialized object
    * @Return (object) oObj : the unserialized object
    */
    public function getObj () {
    return $this -> oObj;
    }

    /**
    * public method __toString
    * displays either the generated xml, or the object's properties to be serialized if the xml has not yet been generated
    * This method requires the XSL extension to be set i
    * Special thanks to Erwy, developpez.com XML forum administrator, who debugged my XSL :-), and to Tiscars, who tried to help too!
    * @Returns (string) sString
    */
    public function __toString () {
    $sString = '';
    if (isset ($this -> xml) && !empty ($this -> xml)) {
    if (class_exists ('XSLTProcessor')) {
    $sString = '<br /><br /><span style="background-color: #ffcc33;">XML DISPLAY</span><br />';
    $sXsl = <<<XSL
    <?xml version ="1.0" encoding ="utf-8" ?>
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:php="http://php.net/xsl"
    extension-element-prefixes="php">
    <xsl:output method="xml" indent="yes" encoding="utf-8" />
    <xsl:namespace-alias stylesheet-prefix="php" result-prefix="xsl" />
    <xsl:template match="/">
    <ul>
    <xsl:apply-templates select="*"/>
    </ul>
    </xsl:template>
    <xsl:template match="*">
    <li>
    <xsl:value-of select="local-name ()"/><xsl:apply-templates select="text()"/>
    <xsl:if test="*"><ul>
    <xsl:apply-templates select="*"/>
    </ul></xsl:if>
    </li>
    </xsl:template>
    <xsl:template match="text()">
    <xsl:value-of select="concat('=&gt;',.)"/>
    </xsl:template>
    </xsl:stylesheet>
    XSL;
    $xsl = new XSLTProcessor();
    $xsl->importStyleSheet(DOMDocument::loadXML($sXsl));
    $sString .= $xsl->transformToXML(DOMDocument::loadXML($this -> xml));
    } else {
    $sString = '<br /><br /><span style="background-color: #ffcc33;">XSL EXTENSION NOT SET IN YOUR PHP.INI</span><br /><br />';
    }
    } else {
    $sString = '<br /><br /><span style="background-color: #ffcc33;">OBJECT PROPERTIES DISPLAY</span><br /><br />';
    $sString .= '<pre>'.var_export ($this -> aProps, true).'</pre>';
    }
    return $sString;
    }

    }
    ?>

    Click to Download File



    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Miscellaneous Code Articles
    More By Codewalkers

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Download a free trial of Lotus Quickr 8.0

    Visit IBM developerWorks to download a free trial version of Lotus Quickr 8.0, which enables collaboration by transforming the way everyday business content such as documents, rich media, photos, and video can be shared. Lotus Quickr makes it faster and easier to share content of all types (not just documents) within virtual teams. It is designed to make it easier to collaborate across organizational boundaries, while continuing to work within the context of familiar desktop applications.
    FREE! Go There Now!


    NEW! Evaluate WebSphere Extended Deployment Compute Grid V6.1

    Visit IBM developerWorks to download a free trial version of WebSphere Extended Deployment Compute Grid, which lets you schedule, execute, and monitor batch jobs. Because online transaction processing and batch jobs execute simultaneously on the same server resources, you can avoid costly duplication of resources. Compute Grid supports job types of Java transactional batch, compute-intensive and a new type called "native execution", which enables non-Java workloads to run on distributed end points.
    FREE! Go There Now!


    NEW! Hello World: Monitor a simple business process using WebSphere Business Monitor V6.0.2

    This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product.
    FREE! Go There Now!


    NEW! Info 2.0: Harnessing the power of Web 2.0 and Enterprise Mashups

    Listen to this webcast to get an overview of Info 2.0 and a technical demo of how to quickly build an enterprise mashup. IBM's Info 2.0 technology leverages emerging Web 2.0 technologies such as mashups, feeds, AJAX, and JSON in order to simplify assembly of information using feeds and services. Come learn about the technical elements of Info 2.0 including the Feed Generation framework, Mashup Engine, and mashup assembly components. Learn how to pull information from databases, departmental information, and the Web to create mashups critical to your company’s success. We will also discuss best practices to help you get started.
    FREE! Go There Now!


    NEW! Maintaining QoS and Process Integrity in an SOA Environment

    This webcast outlines the best practices that must be instituted to gain the maximum benefit from SOA while maintaining high quality of service. Whether you are deploying new applications or managing and monitoring your existing infrastructure, learn how you can ensure high quality of services with SOA based solutions from IBM. All registrants who attend this live Web Seminar will receive complimentary access to a white paper titled “Maintaining QoS in an SOA Environment”.
    FREE! Go There Now!


    NEW! Rational Talks to You: Grady Booch on Architecture

    Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered!
    FREE! Go There Now!


    NEW! Rational Talks to You: Manage RUP-based CMMI initiatives

    Join this Rational Talks to You teleconference on December 4 at 1:00 pm ET to discuss how Rational Method Composer can help meet your compliance objectives. Get your questions answered!
    FREE! Go There Now!


    NEW! Section 508 of the U.S. Rehabilitation Act: Web accessibility compliance

    Because access to government information continues to be an area of concern for many U.S. citizens with disabilities, the U.S. government enacted Section 508 of the Rehabilitation Act in 2001 to ensure that government agencies create accessible Web content, enabling all citizens to access the information they need. A fully accessible Web site makes Web content accessible to all individuals, including those with disabilities, who may be accessing Web content via a variety of user agents. Common user agents include standard Web browsers, text-only browsers, assistive devices and mobile devices such as cell phones or personal digital assistants (PDAs).
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Manual Tester V7.0.1

    Try the latest version of IBM Rational Manual Tester V7.0.1 by downloading a free trial from IBM developerWorks. This manual test authoring and execution tool promotes test step reuse to reduce the impact of software change on testers and business analysts and addresses the needs of teams performing at least a portion of their testing manually.
    FREE! Go There Now!


    NEW! Webcast: Eclipse: Empowering the universal platform

    The Eclipse community is constantly working to extend Eclipse's functionality. In this webcast, learn about some of the most important and feature-rich projects under development. From multi-language support to plug-in development, tune in to see what Eclipse is capable of now.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    MISCELLANEOUS CODE ARTICLES

    - A Web App Based on a Model for the CodeIgnit...
    - Completing a Model for the CodeIgniter PHP F...
    - Validating Input Data with the CodeIgniter P...
    - Deleting Database Records with the CodeIgnit...
    - Inserting Database Records with a CodeIgnite...
    - Fetching Database Rows with a Model for the ...
    - Model Data and Validation Rules for a Generi...
    - Building a Generic Model for the CodeIgniter...
    - upload image to database sql
    - Random Password Generator
    - BCroot, get the root of a number with BC fun...
    - Find pi in a high precision
    - [PHP5] FORMCHECKER : data validation
    - SPL and ITERATOR : examples
    - Xml with Rss Feeds





    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 10 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek