Les Snippets

Connexion

Serialisation et deserialisation d'un objet vers du xml

Niveau requis pour utiliser/comprendre cette source : 1 ( Débutant )
Créé le 17/03/2006 19:51:25 et initié par jesusonline [Liste]
Date de mise à jour : 08/04/2006 14:06:45
Vue : 22955
Catégorie(s) : Trucs & Astuces, XML
Langages dispo pour ce code :
- VB 2005, VB.NET 1.x
- C# 1.x, C# 2.x
- Java
- PHP 5
- C# 2.x
- Voir tous les langages pour ce code snippet



Langage : PHP 5
Date ajout : 22/03/2006
Posté par malalam [Liste]
DateMAJ : 27/03/2006

<?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)) {
   return false;
  } 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', 'iso-8859-1');
  $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;
 }

}
?>

Remarque :
Seules les propriétés PUBLIQUES de l'objet seront linéarisées/délinéarisées (je n'ai pas encore trouvé de moyen d'accéder ainsi aux propriétés protégées ou privées)

Snippets en rapport avec : Serialisation, Deserialisation, Xml, Serialize, Deserialize



Codes sources en rapport avec : Serialisation, Deserialisation, Xml, Serialize, Deserialize

{PDA / PocketPC} POCKETAPPCONFIG : CONSERVER SES PRÉFÉRENCES
Dans de nombreux cas il est inutile d'utiliser une base de donnée pour sauvegarder quelques préféren...

{C# / C#.NET} DESSINER EN XML
C'est le prolongement d'un test d'embauche : On m'a demandé de faire un composant (dll) qui serait c...

{JAVA / J2EE} MANIPULATION DE FICHIER XML
le code creé un fichier XML depuis une base de données Mysql ensuite il auras l'affichage du conten...

{PHP} [PHP5] XML OBJECT SERIALIZER/UNSERIALIZER
Bon...je vais tenter d'expliquer le concept ;-) Les adeptes de la POO PHP connaisse les fonctions s...

{C# / C#.NET} [C#] [XML] SERIALIZATION STRING, COLOR, ARRAYLIST, HASHTABLE, DATETIME
Voici un ensemble de classes qui vont permettre en englobant des classes de bases de C# de faire de ...

{JAVA / J2EE} SÉRIALISATION
c un petit programme qui vous presente d'une maniere tres simple la facon d'utiliser une des methode...

{Flash} XMLIZER : OBJET FONCTIONNANT SUR LE PRINCIPE DE "SERIALIZE()" ET "UNSERIALIZE()" DE PHP.
Après mettre pencher sur le "serialize()" et "unserialize()" de PHP grace a Skreo, je me suis vite r...

{Flash} CLASSE SERIALIZER : SERIALIZE() ET UNSERIALIZE() IDENTIQUES À PHP
La classe Serializer contient 2 fonction publiques : serialize() et unserialize() identiques à php ...

{C# / C#.NET} SÉRIALISEZ VOS FICHIERS DE CONFIGURATION !!!
Combien de fois avez-vous réécris vos méthodes permettant de gérer vos fichiers de configurations ??...

{Flash} BANNIÈRE AVEC PORTRAITS DÉFILANTS AS3
Une bannière de site qui affiche un titre et fait défiler des photos toutes les x secondes- en l'occ...