Accueil > > > [PHP5] XML OBJECT SERIALIZER/UNSERIALIZER
[PHP5] XML OBJECT SERIALIZER/UNSERIALIZER
Information sur la source
Description
Bon...je vais tenter d'expliquer le concept ;-) Les adeptes de la POO PHP connaisse les fonctions serialize() et unserialize(). J'ai voulu, pour ma part, créer une classe générique permettant de linéariser un objet...en XML! Un peu comme XMLEncoder et XMLDecoder pour java. Le but ? Obtenir des fichiers faciles à lire, voire à générer en php autrement qu'en créant un objet (cela peut servir de template), et contenant un objet déjà instancié. Ce que fait cette classe : on lui passe un objet en paramètre. Elle récupère toutes les propriétés PUBLIQUES (j'y reviendrai) de cet objet, et créer une chaîne xml avec. Cette chaîne peut-être récupérée pour, par exemple, l'enregistrer dans un fichier. Elle peut aussi, à partir d'une chaîne XML qu'elle a créée, qu'on lui passe en paramètre ou qu'elle va chercher dans ses propriétés, recréer une instance de cet objet. Dans l'ordre, pour l'utilisation : - on a besoin d'une instance d'une classe dont toutes les propriétés sont publiques. On modifie les propriétés etc... - on instancie xmlSerialize : $oxml = new xmlserialize ($oObj); - on récupère les propriétés de l'objet : $oxml -> getProps (); - on sérialize l'objet : $sXml = $oxml -> xmlToVars (); - on fait ce qu'on veut avec $sXml... Pour le unserialize : on lit le fichier dans lequel on a stocké le xml et on le met dans une chaine : $sXml par exemple, puis : $newObjet = $oxml -> varsToXml ($sXml); Et voilà :-)
Source
- <?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('=>',.)"/>
- </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;
- }
-
- }
- ?>
<?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('=>',.)"/>
</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;
}
}
?>
Historique
- 23 mars 2006 11:10:49 :
- bugfixing
- 23 mars 2006 16:13:07 :
- Gros bug fixing
- 23 mars 2006 16:48:15 :
- modif du descriptif
- 23 mars 2006 17:19:00 :
- bug fixing
- 27 mars 2006 10:44:23 :
- Correction mineure concernant les tableaux indexés numériquement
- 27 mars 2006 11:14:53 :
- correction d'un bug sur les propriétés étant elles-mêmes des objets.
- 27 mars 2006 15:44:58 :
- return false viré du constructeur... ;-)
- 29 mars 2006 10:53:37 :
- j'ai mis en place une première version d'affichage du xml généré. Pour l'utiliset il suffit de faire un echo de l'objet xmlserialize:
$oxml = new xmlserialize ($obj);
echo $oxml; // par exemple
Si le xml a été généré via la méthode varsToXml-), le xml sera affiché grâce à l'utilisation de l'extension XSL de php. IL va sans dire qu'il faut l'activer (elle l'est rarement par défaut) dans le php.ini : avec l'objet XSLTProcessor.
Sinon, un export des propriétés de l'objet pouvant être linéarisées est affiché.
Je précise que ce n'est qu'une première version parce que la mise en forme du XML via des listes est un peu buggy ;-) Je rencontre un petit problème dans la génération de ma XSL. Problème que je cerne très bien, lol, mais je n'ai pas encore trouvé le moyen de le règler.
- 29 mars 2006 11:41:02 :
- Commentaires ajoutés
- 30 mars 2006 13:53:56 :
- version débuggée de ma XSL, grâce à Erwy et Tiscars (voir les credits dans les commentaires de la méthode __toString). L'affichage est maintenant parfait :-)
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
Probleme avec serialize et unserialize [ par matou82 ]
J'ai un objet que je serialize et passe en paramètre dans l'url d'un popup.Dans ce popup je le unserialize. Il s'agit d'un objet possédant une fonctio
PHP / NuSOAP : Xml parsing error [ par pete87150 ]
Bonjour,J'ai créé un service web tout simple pour tester : [WebService(Description="Bienvenue sur le service Web de démo",Namespace="WordGeneration")]
Pb de récupéationde données XML en PHP [ par baka72 ]
Salut,J ai un pb en php qd je veu récupérer mes données XML. en effet, si le contenu de la donnée est assez long PHP me la met en plusieurs morceaux e
Besoin d'aide Php/Xml [ par bipbipbip ]
Bonjour à tousJe cherche a modifier un xml sans passer par des fonctions compliqués que je ne maitrise pas. Je voudrais que mon script php ouvre mon f
Récupérer les données d'un fichier xml [ par iomega ]
Bonjour à tousJe voudrai récupérer la valeur qui se trouvent dans une sous catégorie de la balise <RECORD><ARTICLE> ET ENFIN LA VALEUR QUE
probleme avec xml : à l'aide!! [ par jed35 ]
bonjour,j'explique mon probleme :j'ai le code suivant en php$graph_title = 'Titre de mon diagramme';$graph_desc = 'mon super graphe';$graph_data = arr
xml dans un tableau php! SVG à la clé :) [ par jed35 ]
Bonjour je débute en php et évidemment j'ai un probleme. Je cherche à placer des données (qui se trouvent dans un fichier xml) dans un tableau php.voi
parser xml [ par Nebraska ]
bonjour,bon je débute salement en php; et j'ai besoin d'un parser xml. J'ai essayé ça mais bon ça marche pas :(Une bonne âme prèt a me dire ou je me s
Pb avec XML !!! [ par renaud1102 ]
Salut,J'utilise un fichier XML comme base de données, je sais afficher cette base, je sais ajouter un element mais je ne sais point comment modifier u
ecrir dans un fichier xml déjà existant [ par BirD ]
hello,ca fait un moment que je cherche une astuce qui me permetterais d'écrir dans un document XML (sans passer par la meme méthode que pour écrir dan
|
Derniers Blogs
CSS CONTENT STATE SELECTORS (PERSONNAL DRAFT)CSS CONTENT STATE SELECTORS (PERSONNAL DRAFT) par FREMYCOMPANY
Bonjour à tous, Je viens de publier une proposition comprenant 5 pseudo-classes pour le CSS Working Group ayant trait à l'état de chargement d'un élément (ex: IMG,VIDEO,AUDIO,OBJECT pour l'HTML.). Si le c½ur vous en dit, vous pouvez retrouver cette p...
Cliquez pour lire la suite de l'article par FREMYCOMPANY MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ?MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ? par ROMELARD Fabrice
Formation initiale Durant la formation, le découpage classique est le suivant (je donnerai les équivalences Suisse lorsque je les connaîtrais) : Ecole primaire jusqu'au Collège : Formation générale permettant d'obtenir les méthodes...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice Y'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENTY'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENT par Aleks
Quand on a ce genre d'erreur sans log :
Et bas on a juste envie de choper le gas de Microsoft qu'a développé ça et lui foutre des baffes de Coboye ! ...
Cliquez pour lire la suite de l'article par Aleks [HYPER-V 3] PRéSENTATION DES COMMANDLETS POWERSHELL[HYPER-V 3] PRéSENTATION DES COMMANDLETS POWERSHELL par Pierrick CATRO-BROUILLET
Avec la sortie prochaine de la Beta Consumer Preview de Windows 8, j'avais envie de revenir sur une des fonctionnalités que j'attends le plus et que, en bon geek que je suis, j'utilise déjà : Hyper-V 3 ainsi son module PowerShell.
Il y a déjà pléthor...
Cliquez pour lire la suite de l'article par Pierrick CATRO-BROUILLET IIS7 - COMPRESSION GZIPIIS7 - COMPRESSION GZIP par cyril
La compression GZIP permet d'améliorer les performances de navigation en compressant ce qu'envoie le serveur à un client. Pour comprendre comment cela fonctionne, regardons ce qu'il se passe au niveau HTTP lorsqu'un client tente d'accéder à une ress...
Cliquez pour lire la suite de l'article par cyril
Logiciels
Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning Academy System (17.1.3.0)ACADEMY SYSTEM (17.1.3.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|