WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
PHP Web Logs (BLogs)
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Submit Site
Forex Trading Online forex trading platform

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : Objects to XML Serializer/Unserializer
Categories : PHP, PHP Classes, DOM XML, Serialize Click here to Update Your Picture
Johan Barbier
Date : Mar 22nd 2006
Grade : 4 of 5 (graded 3 times)
Viewed : 4920
File : 4359.zip
Images : No Images for this code example.
Search : More code by Johan Barbier
Action : Grade This Code Example
Tools : My Examples List

  Submit your own code examples 
 

xmlserialize.cls.php
<?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;
    }

}
?>


oweapons.cls.php
<?php
class oweapons {

    const
sPathImg = 'img/weapons/';

    public
$sImg = '';

    private
$sIsA = '';
    private
$aSpecialAtt = array (
       
'poison' => 0,
       
'fire' => 0,
       
'ice' => 0,
       
'earth' => 0,
       
'water' => 0
       
);
    private
$aSpecialDef = array (
       
'poison' => 0,
       
'fire' => 0,
       
'ice' => 0,
       
'earth' => 0,
       
'water' => 0
       
);
    private
$aDefense = array (
       
'sword' => 0,
       
'axe' => 0,
       
'lance' => 0,
       
'club' => 0,
       
'hand' => 0
       
);

    private
$sName = '';
    private
$sType = '';

    public function
__construct ($sName, $sType, $sImg = 'default.png') {
       
$this -> sImg = self::sPathImg.$sImg;
       
$this -> sName = $sName;
       
$this -> sType = $sType;
    }

    public function
getMe ($sProp, $sDetail = '') {
        if (isset (
$this -> $sProp)) {
            if (!empty (
$sDetail)) {
                if (
is_array ($this -> $sProp) && array_key_exists ($sDetail, $this -> sProp)) {
                    return
$this -> $sProp[$sDetail];
                } else {
                    return
false;
                }
            } else {
                return
$this -> $sProp;
            }
        } else {
            return
false;
        }
    }

    public function
setMe ($sProp, array $aProps = array (), $sDetail = '') {
        if ((empty (
$aProps) && empty ($sDetail)) || !isset ($this -> $sProp)) {
            return
false;
        } else {
            if (isset (
$aProps)) {
                foreach (
$aProps as $clef => $val) {
                    if (
array_key_exists ($clef, $this -> $sProp) && is_numeric ($val)) {
                       
$this -> {$sProp}[$clef] = $val;
                    }
                }
            } else {
                if (isset (
$this -> $sProp[$sDetail]) && is_numeric ($sDetail)) {
                   
$this -> {$sProp}[$sDetail] = $sDetail;
                }
            }
        }
    }
}
?>



ocharacters.cls.php
<?php
class ocharacters {

    const
sImgPath = 'img/avatars/';

    public
$aChars = array (
       
'strength' => 0,
       
'dexterity' => 0,
       
'intelligence' => 0,
       
'endurance' => 0,
       
'swiftness' => 0
       
);

    public
$aAttacks = array (
       
'sword' => 0,
       
'axe' => 0,
       
'lance' => 0,
       
'club' => 0,
       
'hand' => 0
       
);
    public
$aDefenseWith = array (
       
'sword' => 0,
       
'axe' => 0,
       
'lance' => 0,
       
'club' => 0,
       
'hand' => 0,
       
'shield' => 0
       
);
    public
$aDefenseAgainst = array (
       
'sword' => 0,
       
'axe' => 0,
       
'lance' => 0,
       
'club' => 0,
       
'hand' => 0
       
);
    public
$aSpecialAtt = array (
       
'poison' => 0,
       
'fire' => 0,
       
'ice' => 0,
       
'earth' => 0,
       
'water' => 0
       
);
    public
$aSpecialDef = array (
       
'poison' => 0,
       
'fire' => 0,
       
'ice' => 0,
       
'earth' => 0,
       
'water' => 0
       
);
    public
$aSpecialMisc = array (
       
'autoHeal' => 0
       
);
    public
$oArmour = null;
    public
$oWeapon = null;
    public
$oEquipment = null;
    public
$aWeapons = array ();
    public
$aArmours = array ();
    public
$aEquipments = array ();

    public
$PV = 0;
    public
$XP = 0;
    public
$sImg = '';


    public function
__construct ($sImg = 'default.png') {
       
$this -> sImg = self::sImgPath.$sImg;
    }

    public function
getMe ($sProp, $sDetail = '') {
        if (isset (
$this -> $sProp)) {
            if (!empty (
$sDetail)) {
                if (
is_array ($this -> $sProp) && array_key_exists ($sDetail, $this -> sProp)) {
                    return
$this -> $sProp[$sDetail];
                } else {
                    return
false;
                }
            } else {
                return
$this -> $sProp;
            }
        } else {
            return
false;
        }
    }

    public function
setMe ($sProp, array $aProps = array (), $sDetail = '') {
        if ((empty (
$aProps) && empty ($sDetail)) || !isset ($this -> $sProp)) {
            return
false;
        } else {
            if (isset (
$aProps)) {
                foreach (
$aProps as $clef => $val) {
                    if (
array_key_exists ($clef, $this -> $sProp) && is_numeric ($val)) {
                       
$this -> {$sProp}[$clef] = $val;
                    }
                }
            } else {
                if (isset (
$this -> $sProp[$sDetail]) && is_numeric ($sDetail)) {
                   
$this -> {$sProp}[$sDetail] = $sDetail;
                }
            }
        }
    }

    public function
equipMe ($sProp, $oObj) {
        if (!isset (
$sProp) || !is_object ($oObj)) {
            return
false;
        } else {
           
$this -> {$sProp} = $oObj;
        }
    }

    public function
addEquip ($sProp, $sName) {
        if (!isset (
$sProp)) {
            return
false;
        } else {
           
$this -> {$sProp}[] = $sName;
        }
    }

    public function
isHit ($iAtt, $sWeaponType, array $aSpecials = array ()) {
    }

/*
    public function xmlSerialize () {
        $aProps = get_object_vars ($this);
        $xml = new DOMDocument ('1.0', 'iso-8859-1');
        foreach ($aProps as $clef => $val) {
            $domClef = $xml -> createElement ((string)$clef);
            $domClef = $xml -> appendChild ($domClef);
            if (is_scalar ($val)) {
                $valClef = $xml -> createTextNode ((string)$val);
                $valClef = $domClef -> appendChild ($valClef);
            } else {
                if (is_array ($val)) {
                    foreach ($val as $key => $value) {
                        if (empty ($key)) {
                            $key = '_'.$key;
                        }
                        $valKey = $xml -> createElement ((string)$key);
                        $valKey = $domClef -> appendChild ($valKey);
                        if (is_scalar ($value)) {
                            $valueClef = $xml -> createTextNode ((string)$value);
                            $valueClef = $valKey -> appendChild ($valueClef);
                        }
                    }
                }
            }
        }
        return $xml -> saveXML ();
    }
*/
}
?>


index.php
<?php
/**
* include stuff
*/
require_once 'class/ocharacters.cls.php';
require_once
'class/oweapons.cls.php';
require_once
'class/xmlserialize.cls.php';

/**
* main class instanciation
*/
$ohero = new ocharacters;

/**
* defining some characteristics =! from the one by default
*/
$ohero -> setMe ('aChars', array ('strength' => 9,'dexterity' => 6,'intelligence' => 3,'endurance' => 8,'swiftness' => 7));
$ohero -> setMe ('aAttacks', array ('sword' => 5,
       
'axe' => 0,
       
'lance' => 0,
       
'club' => 0,
       
'hand' => 0));
$ohero -> setMe ('aDefenseWith', array ('sword' => 1,
       
'axe' => 0,
       
'lance' => 0,
       
'club' => 0,
       
'hand' => 0,
       
'shield' => 0));
$ohero -> setMe ('aDefenseAgainst', array ('sword' => 2,
       
'axe' => 1,
       
'lance' => 0,
       
'club' => 5,
       
'hand' => 10));

/**
* adding an oweapon object to the hero
*/
$osword = new oweapons ('Basic Sword', 'sword');
$ohero -> addEquip ('aWeapons', $osword -> getMe ('sName'));
$ohero -> equipMe ('oWeapon', $osword);

$ohero -> aChars['strength'] = 23;

/**
* xmlserializer instanciation with the created object
*/
$oxml = new xmlserialize ($ohero);
$oxml -> getProps ();

/**
* echo the object's properties
*/
echo $oxml;
$sXml = $oxml -> varsToXml ();

/**
* echo the xml serialization
*/
echo htmlentities ($sXml);
echo
$oxml;

/**
* create a new empty hero object, to be sure it works fine :-) Charcateristics will be the default ones
*/
$oNewHero = new ocharacters;
/**
* now we will get the object again
*/
$oNewXml = new xmlserialize ($oNewHero, array ($osword));

/**
* get the object
*/
$oNewXml -> xmlToVars ($sXml);

/**
* we assign the obtained object to our new instance of a hero
*/
$oNewHero2 = $oNewXml -> getObj ();

/**
* echo the obtained hero : yep, everything is here :-)
*/

echo '<br /><br />';
echo
'<pre>', print_r ($oNewHero2), '</pre>';
?>



XPath for PHP without the DOM XML extension
Categories : DOM XML, XML, XSLT, PHP Classes, PHP
O-LOC : PHP 5.x Internationalization class and back-office. manage the display of translations on a localized web application.
Categories : PHP, PHP Classes, Web Applications, Languages, DOM XML
file class , uploade file , download file already uploaded on another website
Categories : PHP, PHP Classes, Filesystem, Web Services
PHP Paypal IPN Integration Class v1.0.0
Categories : PHP, PHP Classes, Payment Gateways
crop and resize image class using gd library function
Categories : PHP, PHP Classes, GD image library, Graphics
A Timing Class
Categories : PHP, PHP Classes, Date Time
The class to check load time of your script VERY usefull for relatively slow applications, but not only..
Categories : PHP, PHP Classes, Debugging
Create HTML forms dynamicly using Javascript & PHP
Categories : PHP, PHP Classes, Java Script
usercounter class
Categories : PHP, PHP Classes, Databases, MySQL, Environment Variables
RSS parser. Parses RSS into an array. Quick and nasty but does the job. No checking is done for correct Tags, only correct XML. PHP4 needed to display result (uses print_r).
Categories : PHP, XML, PHP Classes, Rich Site Summary (RSS)
ElfReader: An ELF (Executable and Linking Format) header information in PHP. Shows how to use the UNPACK function to read data.
Categories : PHP, Linux, PHP Classes
Is_serialized() before passing variables to unserialize()
Categories : PHP, Serialize
an example of the cyberlib payment class
Categories : PHP, PHP Classes, Ecommerce, Credit Cards
Power Form Validation
Categories : PHP, PHP Classes, Data Validation
MySQL Handler
Categories : PHP, Databases, MySQL, Classes and Objects, PHP Classes