XML_Serializer
[ class tree: XML_Serializer ] [ index: XML_Serializer ] [ all elements ]

Source for file Unserializer.php

Documentation is available at Unserializer.php

  1. <?PHP
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. // +----------------------------------------------------------------------+
  4. // | PHP Version 4                                                        |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 1997-2002 The PHP Group                                |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 2.0 of the PHP license,       |
  9. // | that is bundled with this package in the file LICENSE, and is        |
  10. // | available at through the world-wide-web at                           |
  11. // | http://www.php.net/license/2_02.txt.                                 |
  12. // | If you did not receive a copy of the PHP license and are unable to   |
  13. // | obtain it through the world-wide-web, please send a note to          |
  14. // | license@php.net so we can mail you a copy immediately.               |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Stephan Schmidt <schst@php-tools.net>                       |
  17. // +----------------------------------------------------------------------+
  18. //
  19. //    $Id: Unserializer.php,v 1.19 2004/08/24 10:30:35 schst Exp $
  20.  
  21. /**
  22.  * uses PEAR error managemt
  23.  */
  24. require_once 'PEAR.php';
  25.  
  26. /**
  27.  * uses XML_Parser to unserialize document
  28.  */
  29. require_once 'XML/Parser.php';
  30.  
  31. /**
  32.  * error code for no serialization done
  33.  */
  34. define('XML_UNSERIALIZER_ERROR_NO_UNSERIALIZATION'151);
  35.  
  36. /**
  37.  * XML_Unserializer
  38.  *
  39.  * class to unserialize XML documents that have been created with
  40.  * XML_Serializer. To unserialize an XML document you have to add
  41.  * type hints to the XML_Serializer options.
  42.  *
  43.  * If no type hints are available, XML_Unserializer will guess how
  44.  * the tags should be treated, that means complex structures will be
  45.  * arrays and tags with only CData in them will be strings.
  46.  *
  47.  * <code>
  48.  * require_once 'XML/Unserializer.php';
  49.  *
  50.  * //  be careful to always use the ampersand in front of the new operator
  51.  * $unserializer = &new XML_Unserializer();
  52.  *
  53.  * $unserializer->unserialize($xml);
  54.  *
  55.  * $data = $unserializer->getUnserializedData();
  56.  * <code>
  57.  *
  58.  * Possible options for the Unserializer are:
  59.  *
  60.  * 1. complexTypes => array|object
  61.  * This is needed, when unserializing XML files w/o type hints. If set to
  62.  * 'array' (default), all nested tags will be arrays, if set to 'object'
  63.  * all nested tags will be objects, that means you have read access like:
  64.  *
  65.  * <code>
  66.  * require_once 'XML/Unserializer.php';
  67.  * $options = array('complexType' => 'object');
  68.  * $unserializer = &new XML_Unserializer($options);
  69.  *
  70.  * $unserializer->unserialize('http://pear.php.net/rss.php');
  71.  *
  72.  * $rss = $unserializer->getUnserializedData();
  73.  * echo $rss->channel->item[3]->title;
  74.  * </code>
  75.  *
  76.  * 2. keyAttribute
  77.  * This lets you specify an attribute inside your tags, that are used as key
  78.  * for associative arrays or object properties.
  79.  * You will need this if you have XML that looks like this:
  80.  *
  81.  * <users>
  82.  *   <user handle="schst">Stephan Schmidt</user>
  83.  *   <user handle="ssb">Stig S. Bakken</user>
  84.  * </users>
  85.  *
  86.  * Then you can use:
  87.  * <code>
  88.  * require_once 'XML/Unserializer.php';
  89.  * $options = array('keyAttribute' => 'handle');
  90.  * $unserializer = &new XML_Unserializer($options);
  91.  *
  92.  * $unserializer->unserialize($xml, false);
  93.  *
  94.  * $users = $unserializer->getUnserializedData();
  95.  * </code>
  96.  *
  97.  * @category XML
  98.  * @package  XML_Serializer
  99.  * @version  0.9.1
  100.  * @author   Stephan Schmidt <schst@php-tools.net>
  101.  * @uses     XML_Parser
  102.  */
  103. class XML_Unserializer extends XML_Parser {
  104.  
  105.    /**
  106.     * default options for the serialization
  107.     * @access private
  108.     * @var array $_defaultOptions 
  109.     */
  110.     var $_defaultOptions = array(
  111.                          'complexType'       => 'array',                // complex types will be converted to arrays, if no type hint is given
  112.                          'keyAttribute'      => '_originalKey',         // get array key/property name from this attribute
  113.                          'typeAttribute'     => '_type',                // get type from this attribute
  114.                          'classAttribute'    => '_class',               // get class from this attribute (if not given, use tag name)
  115.                          'parseAttributes'   => false,                  // parse the attributes of the tag into an array
  116.                          'attributesArray'   => false,                  // parse them into sperate array (specify name of array here)
  117.                          'prependAttributes' => '',                     // prepend attribute names with this string
  118.                          'contentName'       => '_content',             // put cdata found in a tag that has been converted to a complex type in this key
  119.                          'tagMap'            => array(),                // use this to map tagnames
  120.                          'forceEnum'         => array()                 // these tags will always be an indexed array
  121.                         );
  122.  
  123.    /**
  124.     * actual options for the serialization
  125.     * @access private
  126.     * @var array $options 
  127.     */
  128.     var $options = array();
  129.  
  130.    /**
  131.     * do not use case folding
  132.     * @var boolean $folding 
  133.     */
  134.     var $folding = false;
  135.  
  136.    /**
  137.     * unserilialized data
  138.     * @var string $_serializedData 
  139.     */
  140.     var $_unserializedData = null;
  141.  
  142.    /**
  143.     * name of the root tag
  144.     * @var string $_root 
  145.     */
  146.     var $_root = null;
  147.  
  148.    /**
  149.     * stack for all data that is found
  150.     * @var array    $_dataStack 
  151.     */
  152.     var $_dataStack  =   array();
  153.  
  154.    /**
  155.     * stack for all values that are generated
  156.     * @var array    $_valStack 
  157.     */
  158.     var $_valStack  =   array();
  159.  
  160.    /**
  161.     * current tag depth
  162.     * @var int    $_depth 
  163.     */
  164.     var $_depth = 0;
  165.  
  166.    /**
  167.     * constructor
  168.     *
  169.     * @access   public
  170.     * @param    mixed   $options    array containing options for the serialization
  171.     */
  172.     function XML_Unserializer($options = null)
  173.     {
  174.         // reset parser and properties
  175.         $this->XML_Parser(null,'event');
  176.  
  177.         if (is_array($options)) {
  178.             $this->options array_merge($this->_defaultOptions$options);
  179.         else {
  180.             $this->options $this->_defaultOptions;
  181.         }
  182.     }
  183.  
  184.    /**
  185.     * return API version
  186.     *
  187.     * @access   public
  188.     * @static
  189.     * @return   string  $version API version
  190.     */
  191.     function apiVersion()
  192.     {
  193.         return '0.9';
  194.     }
  195.  
  196.    /**
  197.     * reset all options to default options
  198.     *
  199.     * @access   public
  200.     * @see      setOption(), XML_Unserializer(), setOptions()
  201.     */
  202.     function resetOptions()
  203.     {
  204.         $this->options $this->_defaultOptions;
  205.     }
  206.  
  207.    /**
  208.     * set an option
  209.     *
  210.     * You can use this method if you do not want to set all options in the constructor
  211.     *
  212.     * @access   public
  213.     * @see      resetOption(), XML_Unserializer(), setOptions()
  214.     */
  215.     function setOption($name$value)
  216.     {
  217.         $this->options[$name$value;
  218.     }
  219.  
  220.    /**
  221.     * sets several options at once
  222.     *
  223.     * You can use this method if you do not want to set all options in the constructor
  224.     *
  225.     * @access   public
  226.     * @see      resetOption(), XML_Unserializer(), setOption()
  227.     */
  228.     function setOptions($options)
  229.     {
  230.         $this->options array_merge($this->options$options);
  231.     }
  232.  
  233.    /**
  234.     * unserialize data
  235.     *
  236.     * @access   public
  237.     * @param    mixed    $data   data to unserialize (string, filename or resource)
  238.     * @param    boolean  $isFile string should be treated as a file
  239.     * @param    array    $options 
  240.     * @return   boolean  $success
  241.     */
  242.     function unserialize($data$isFile = false$options = null)
  243.     {
  244.         $this->_unserializedData = null;
  245.         $this->_root = null;
  246.  
  247.         // if options have been specified, use them instead
  248.         // of the previously defined ones
  249.         if (is_array($options)) {
  250.             $optionsBak $this->options;
  251.             if (isset($options['overrideOptions']&& $options['overrideOptions'== true{
  252.                 $this->options array_merge($this->_defaultOptions$options);
  253.             else {
  254.                 $this->options array_merge($this->options$options);
  255.             }
  256.         }
  257.         else {
  258.             $optionsBak = null;
  259.         }
  260.  
  261.         $this->_valStack = array();
  262.         $this->_dataStack = array();
  263.         $this->_depth = 0;
  264.  
  265.         if (is_string($data)) {
  266.             if ($isFile{
  267.                 $result $this->setInputFile($data);
  268.                 if (PEAR::isError($result)) {
  269.                     return $result;
  270.                 }
  271.                 $result $this->parse();
  272.             else {
  273.                 $result $this->parseString($data,true);
  274.             }
  275.         else {
  276.            $this->setInput($data);
  277.            $result $this->parse();
  278.         }
  279.  
  280.         if ($optionsBak !== null{
  281.             $this->options $optionsBak;
  282.         }
  283.  
  284.         if (PEAR::isError($result)) {
  285.             return $result;
  286.         }
  287.  
  288.         return  true;
  289.     }
  290.  
  291.    /**
  292.     *   get the result of the serialization
  293.     *
  294.     *   @access public
  295.     *   @return string  $serializedData
  296.     */
  297.         function getUnserializedData()
  298.         {
  299.             if ($this->_root === null {
  300.                 return  $this->raiseError('No unserialized data available. Use XML_Unserializer::unserialize() first.'XML_UNSERIALIZER_ERROR_NO_UNSERIALIZATION);
  301.             }
  302.             return $this->_unserializedData;
  303.         }
  304.  
  305.    /**
  306.     *   get the name of the root tag
  307.     *
  308.     *   @access public
  309.     *   @return string  $rootName
  310.     */
  311.         function getRootName()
  312.         {
  313.             if ($this->_root === null {
  314.                 return  $this->raiseError('No unserialized data available. Use XML_Unserializer::unserialize() first.'XML_UNSERIALIZER_ERROR_NO_UNSERIALIZATION);
  315.             }
  316.             return $this->_root;
  317.         }
  318.  
  319.     /**
  320.      * Start element handler for XML parser
  321.      *
  322.      * @access private
  323.      * @param  object $parser  XML parser object
  324.      * @param  string $element XML element
  325.      * @param  array  $attribs attributes of XML tag
  326.      * @return void 
  327.      */
  328.     function startHandler($parser$element$attribs)
  329.     {
  330.         if (isset($attribs[$this->options['typeAttribute']])) {
  331.             $type $attribs[$this->options['typeAttribute']];
  332.         else {
  333.             $type 'string';
  334.         }
  335.  
  336.         $this->_depth++;
  337.         $this->_dataStack[$this->_depth= null;
  338.  
  339.         $val = array(
  340.                      'name'         => $element,
  341.                      'value'        => null,
  342.                      'type'         => $type,
  343.                      'childrenKeys' => array(),
  344.                      'aggregKeys'   => array()
  345.                     );
  346.  
  347.         if ($this->options['parseAttributes'== true && (count($attribs> 0)) {
  348.             $val['children'= array();
  349.             $val['type'$this->options['complexType'];
  350.  
  351.             if ($this->options['attributesArray'!= false{
  352.                 $val['children'][$this->options['attributesArray']] $attribs;
  353.             else {
  354.                 foreach ($attribs as $attrib => $value{
  355.                     $val['children'][$this->options['prependAttributes'].$attrib$value;
  356.                 }
  357.             }
  358.         }
  359.  
  360.         if (isset($attribs[$this->options['keyAttribute']])) {
  361.             $val['name'$attribs[$this->options['keyAttribute']];
  362.         }
  363.  
  364.         if (isset($attribs[$this->options['classAttribute']])) {
  365.             $val['class'$attribs[$this->options['classAttribute']];
  366.         }
  367.  
  368.         array_push($this->_valStack$val);
  369.     }
  370.  
  371.     /**
  372.      * End element handler for XML parser
  373.      *
  374.      * @access private
  375.      * @param  object XML parser object
  376.      * @param  string 
  377.      * @return void 
  378.      */
  379.     function endHandler($parser$element)
  380.     {
  381.         $value array_pop($this->_valStack);
  382.         $data  trim($this->_dataStack[$this->_depth]);
  383.  
  384.         // adjust type of the value
  385.         switch(strtolower($value['type'])) {
  386.             /*
  387.              * unserialize an object
  388.              */
  389.             case 'object':
  390.                 if(isset($value['class'])) {
  391.                     $classname  $value['class'];
  392.                 else {
  393.                     $classname '';
  394.                 }
  395.                 if (is_array($this->options['tagMap']&& isset($this->options['tagMap'][$classname])) {
  396.                     $classname $this->options['tagMap'][$classname];
  397.                 }
  398.  
  399.                 // instantiate the class
  400.                 if (class_exists($classname)) {
  401.                     $value['value'&new $classname;
  402.                 else {
  403.                     $value['value'&new stdClass;
  404.                 }
  405.                 if ($data !== ''{
  406.                     $value['children'][$this->options['contentName']] $data;
  407.                 }
  408.  
  409.                 // set properties
  410.                 foreach($value['children'as $prop => $propVal{
  411.                     // check whether there is a special method to set this property
  412.                     $setMethod 'set'.$prop;
  413.                     if (method_exists($value['value']$setMethod)) {
  414.                         call_user_func(array(&$value['value']$setMethod)$propVal);
  415.                     else {
  416.                         $value['value']->$prop $propVal;
  417.                     }
  418.                 }
  419.                 //  check for magic function
  420.                 if (method_exists($value['value']'__wakeup')) {
  421.                     $value['value']->__wakeup();
  422.                 }
  423.                 break;
  424.  
  425.             /*
  426.              * unserialize an array
  427.              */
  428.             case 'array':
  429.                 if ($data !== ''{
  430.                     $value['children'][$this->options['contentName']] $data;
  431.                 }
  432.                 if (isset($value['children'])) {
  433.                     $value['value'$value['children'];
  434.                 else {
  435.                     $value['value'= array();
  436.                 }
  437.                 break;
  438.  
  439.             /*
  440.              * unserialize a null value
  441.              */
  442.             case 'null':
  443.                 $data = null;
  444.                 break;
  445.  
  446.             /*
  447.              * unserialize a resource => this is not possible :-(
  448.              */
  449.             case 'resource':
  450.                 $value['value'$data;
  451.                 break;
  452.  
  453.             /*
  454.              * unserialize any scalar value
  455.              */
  456.             default:
  457.                 settype($data$value['type']);
  458.                 $value['value'$data;
  459.                 break;
  460.         }
  461.         $parent array_pop($this->_valStack);
  462.         if ($parent === null{
  463.             $this->_unserializedData &$value['value'];
  464.             $this->_root &$value['name'];
  465.             return true;
  466.         else {
  467.             // parent has to be an array
  468.             if (!isset($parent['children']|| !is_array($parent['children'])) {
  469.                 $parent['children'= array();
  470.                 if (!in_array($parent['type']array('array''object'))) {
  471.                     $parent['type'$this->options['complexType'];
  472.                     if ($this->options['complexType'== 'object'{
  473.                         $parent['class'$parent['name'];
  474.                     }
  475.                 }
  476.             }
  477.  
  478.             if (!empty($value['name'])) {
  479.                 // there already has been a tag with this name
  480.                 if (in_array($value['name']$parent['childrenKeys']|| in_array($value['name']$this->options['forceEnum'])) {
  481.                     // no aggregate has been created for this tag
  482.                     if (!in_array($value['name']$parent['aggregKeys'])) {
  483.                         if (isset($parent['children'][$value['name']])) {
  484.                             $parent['children'][$value['name']] = array($parent['children'][$value['name']]);
  485.                         else {
  486.                             $parent['children'][$value['name']] = array();
  487.                         }
  488.                         array_push($parent['aggregKeys']$value['name']);
  489.                     }
  490.                     array_push($parent['children'][$value['name']]$value['value']);
  491.                 else {
  492.                     $parent['children'][$value['name']] &$value['value'];
  493.                     array_push($parent['childrenKeys']$value['name']);
  494.                 }
  495.             else {
  496.                 array_push($parent['children'],$value['value']);
  497.             }
  498.             array_push($this->_valStack$parent);
  499.         }
  500.  
  501.         $this->_depth--;
  502.     }
  503.  
  504.     /**
  505.      * Handler for character data
  506.      *
  507.      * @access private
  508.      * @param  object XML parser object
  509.      * @param  string CDATA
  510.      * @return void 
  511.      */
  512.     function cdataHandler($parser$cdata)
  513.     {
  514.         $this->_dataStack[$this->_depth.= $cdata;
  515.     }
  516. }
  517. ?>

Documentation generated on Mon, 11 Mar 2019 13:55:04 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.