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.20 2004/10/28 18:27:09 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.12.0
  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.                          'encoding'          => null                    // specify the encoding character of the document to parse
  122.                         );
  123.  
  124.    /**
  125.     * actual options for the serialization
  126.     * @access private
  127.     * @var array $options 
  128.     */
  129.     var $options = array();
  130.  
  131.    /**
  132.     * do not use case folding
  133.     * @var boolean $folding 
  134.     */
  135.     var $folding = false;
  136.  
  137.    /**
  138.     * unserilialized data
  139.     * @var string $_serializedData 
  140.     */
  141.     var $_unserializedData = null;
  142.  
  143.    /**
  144.     * name of the root tag
  145.     * @var string $_root 
  146.     */
  147.     var $_root = null;
  148.  
  149.    /**
  150.     * stack for all data that is found
  151.     * @var array    $_dataStack 
  152.     */
  153.     var $_dataStack  =   array();
  154.  
  155.    /**
  156.     * stack for all values that are generated
  157.     * @var array    $_valStack 
  158.     */
  159.     var $_valStack  =   array();
  160.  
  161.    /**
  162.     * current tag depth
  163.     * @var int    $_depth 
  164.     */
  165.     var $_depth = 0;
  166.  
  167.    /**
  168.     * constructor
  169.     *
  170.     * @access   public
  171.     * @param    mixed   $options    array containing options for the serialization
  172.     */
  173.     function XML_Unserializer($options = null)
  174.     {
  175.         if (is_array($options)) {
  176.             $this->options array_merge($this->_defaultOptions$options);
  177.         else {
  178.             $this->options $this->_defaultOptions;
  179.         }
  180.  
  181.         // reset parser and properties
  182.         $this->XML_Parser($this->options['encoding'],'event');
  183.     }
  184.  
  185.    /**
  186.     * return API version
  187.     *
  188.     * @access   public
  189.     * @static
  190.     * @return   string  $version API version
  191.     */
  192.     function apiVersion()
  193.     {
  194.         return '0.12';
  195.     }
  196.  
  197.    /**
  198.     * reset all options to default options
  199.     *
  200.     * @access   public
  201.     * @see      setOption(), XML_Unserializer(), setOptions()
  202.     */
  203.     function resetOptions()
  204.     {
  205.         $this->options $this->_defaultOptions;
  206.     }
  207.  
  208.    /**
  209.     * set an option
  210.     *
  211.     * You can use this method if you do not want to set all options in the constructor
  212.     *
  213.     * @access   public
  214.     * @see      resetOption(), XML_Unserializer(), setOptions()
  215.     */
  216.     function setOption($name$value)
  217.     {
  218.         $this->options[$name$value;
  219.     }
  220.  
  221.    /**
  222.     * sets several options at once
  223.     *
  224.     * You can use this method if you do not want to set all options in the constructor
  225.     *
  226.     * @access   public
  227.     * @see      resetOption(), XML_Unserializer(), setOption()
  228.     */
  229.     function setOptions($options)
  230.     {
  231.         $this->options array_merge($this->options$options);
  232.     }
  233.  
  234.    /**
  235.     * unserialize data
  236.     *
  237.     * @access   public
  238.     * @param    mixed    $data   data to unserialize (string, filename or resource)
  239.     * @param    boolean  $isFile string should be treated as a file
  240.     * @param    array    $options 
  241.     * @return   boolean  $success
  242.     */
  243.     function unserialize($data$isFile = false$options = null)
  244.     {
  245.         $this->_unserializedData = null;
  246.         $this->_root = null;
  247.  
  248.         // if options have been specified, use them instead
  249.         // of the previously defined ones
  250.         if (is_array($options)) {
  251.             $optionsBak $this->options;
  252.             if (isset($options['overrideOptions']&& $options['overrideOptions'== true{
  253.                 $this->options array_merge($this->_defaultOptions$options);
  254.             else {
  255.                 $this->options array_merge($this->options$options);
  256.             }
  257.         }
  258.         else {
  259.             $optionsBak = null;
  260.         }
  261.  
  262.         $this->_valStack = array();
  263.         $this->_dataStack = array();
  264.         $this->_depth = 0;
  265.  
  266.         if (is_string($data)) {
  267.             if ($isFile{
  268.                 $result $this->setInputFile($data);
  269.                 if (PEAR::isError($result)) {
  270.                     return $result;
  271.                 }
  272.                 $result $this->parse();
  273.             else {
  274.                 $result $this->parseString($data,true);
  275.             }
  276.         else {
  277.            $this->setInput($data);
  278.            $result $this->parse();
  279.         }
  280.  
  281.         if ($optionsBak !== null{
  282.             $this->options $optionsBak;
  283.         }
  284.  
  285.         if (PEAR::isError($result)) {
  286.             return $result;
  287.         }
  288.  
  289.         return  true;
  290.     }
  291.  
  292.    /**
  293.     *   get the result of the serialization
  294.     *
  295.     *   @access public
  296.     *   @return string  $serializedData
  297.     */
  298.         function getUnserializedData()
  299.         {
  300.             if ($this->_root === null {
  301.                 return  $this->raiseError('No unserialized data available. Use XML_Unserializer::unserialize() first.'XML_UNSERIALIZER_ERROR_NO_UNSERIALIZATION);
  302.             }
  303.             return $this->_unserializedData;
  304.         }
  305.  
  306.    /**
  307.     *   get the name of the root tag
  308.     *
  309.     *   @access public
  310.     *   @return string  $rootName
  311.     */
  312.         function getRootName()
  313.         {
  314.             if ($this->_root === null {
  315.                 return  $this->raiseError('No unserialized data available. Use XML_Unserializer::unserialize() first.'XML_UNSERIALIZER_ERROR_NO_UNSERIALIZATION);
  316.             }
  317.             return $this->_root;
  318.         }
  319.  
  320.     /**
  321.      * Start element handler for XML parser
  322.      *
  323.      * @access private
  324.      * @param  object $parser  XML parser object
  325.      * @param  string $element XML element
  326.      * @param  array  $attribs attributes of XML tag
  327.      * @return void 
  328.      */
  329.     function startHandler($parser$element$attribs)
  330.     {
  331.         if (isset($attribs[$this->options['typeAttribute']])) {
  332.             $type $attribs[$this->options['typeAttribute']];
  333.         else {
  334.             $type 'string';
  335.         }
  336.  
  337.         $this->_depth++;
  338.         $this->_dataStack[$this->_depth= null;
  339.  
  340.         $val = array(
  341.                      'name'         => $element,
  342.                      'value'        => null,
  343.                      'type'         => $type,
  344.                      'childrenKeys' => array(),
  345.                      'aggregKeys'   => array()
  346.                     );
  347.  
  348.         if ($this->options['parseAttributes'== true && (count($attribs> 0)) {
  349.             $val['children'= array();
  350.             $val['type'$this->options['complexType'];
  351.  
  352.             if ($this->options['attributesArray'!= false{
  353.                 $val['children'][$this->options['attributesArray']] $attribs;
  354.             else {
  355.                 foreach ($attribs as $attrib => $value{
  356.                     $val['children'][$this->options['prependAttributes'].$attrib$value;
  357.                 }
  358.             }
  359.         }
  360.  
  361.         if (isset($attribs[$this->options['keyAttribute']])) {
  362.             $val['name'$attribs[$this->options['keyAttribute']];
  363.         }
  364.  
  365.         if (isset($attribs[$this->options['classAttribute']])) {
  366.             $val['class'$attribs[$this->options['classAttribute']];
  367.         }
  368.  
  369.         array_push($this->_valStack$val);
  370.     }
  371.  
  372.     /**
  373.      * End element handler for XML parser
  374.      *
  375.      * @access private
  376.      * @param  object XML parser object
  377.      * @param  string 
  378.      * @return void 
  379.      */
  380.     function endHandler($parser$element)
  381.     {
  382.         $value array_pop($this->_valStack);
  383.         $data  trim($this->_dataStack[$this->_depth]);
  384.  
  385.         // adjust type of the value
  386.         switch(strtolower($value['type'])) {
  387.             /*
  388.              * unserialize an object
  389.              */
  390.             case 'object':
  391.                 if(isset($value['class'])) {
  392.                     $classname  $value['class'];
  393.                 else {
  394.                     $classname '';
  395.                 }
  396.                 if (is_array($this->options['tagMap']&& isset($this->options['tagMap'][$classname])) {
  397.                     $classname $this->options['tagMap'][$classname];
  398.                 }
  399.  
  400.                 // instantiate the class
  401.                 if (class_exists($classname)) {
  402.                     $value['value'&new $classname;
  403.                 else {
  404.                     $value['value'&new stdClass;
  405.                 }
  406.                 if ($data !== ''{
  407.                     $value['children'][$this->options['contentName']] $data;
  408.                 }
  409.  
  410.                 // set properties
  411.                 foreach($value['children'as $prop => $propVal{
  412.                     // check whether there is a special method to set this property
  413.                     $setMethod 'set'.$prop;
  414.                     if (method_exists($value['value']$setMethod)) {
  415.                         call_user_func(array(&$value['value']$setMethod)$propVal);
  416.                     else {
  417.                         $value['value']->$prop $propVal;
  418.                     }
  419.                 }
  420.                 //  check for magic function
  421.                 if (method_exists($value['value']'__wakeup')) {
  422.                     $value['value']->__wakeup();
  423.                 }
  424.                 break;
  425.  
  426.             /*
  427.              * unserialize an array
  428.              */
  429.             case 'array':
  430.                 if ($data !== ''{
  431.                     $value['children'][$this->options['contentName']] $data;
  432.                 }
  433.                 if (isset($value['children'])) {
  434.                     $value['value'$value['children'];
  435.                 else {
  436.                     $value['value'= array();
  437.                 }
  438.                 break;
  439.  
  440.             /*
  441.              * unserialize a null value
  442.              */
  443.             case 'null':
  444.                 $data = null;
  445.                 break;
  446.  
  447.             /*
  448.              * unserialize a resource => this is not possible :-(
  449.              */
  450.             case 'resource':
  451.                 $value['value'$data;
  452.                 break;
  453.  
  454.             /*
  455.              * unserialize any scalar value
  456.              */
  457.             default:
  458.                 settype($data$value['type']);
  459.                 $value['value'$data;
  460.                 break;
  461.         }
  462.         $parent array_pop($this->_valStack);
  463.         if ($parent === null{
  464.             $this->_unserializedData &$value['value'];
  465.             $this->_root &$value['name'];
  466.             return true;
  467.         else {
  468.             // parent has to be an array
  469.             if (!isset($parent['children']|| !is_array($parent['children'])) {
  470.                 $parent['children'= array();
  471.                 if (!in_array($parent['type']array('array''object'))) {
  472.                     $parent['type'$this->options['complexType'];
  473.                     if ($this->options['complexType'== 'object'{
  474.                         $parent['class'$parent['name'];
  475.                     }
  476.                 }
  477.             }
  478.  
  479.             if (!empty($value['name'])) {
  480.                 // there already has been a tag with this name
  481.                 if (in_array($value['name']$parent['childrenKeys']|| in_array($value['name']$this->options['forceEnum'])) {
  482.                     // no aggregate has been created for this tag
  483.                     if (!in_array($value['name']$parent['aggregKeys'])) {
  484.                         if (isset($parent['children'][$value['name']])) {
  485.                             $parent['children'][$value['name']] = array($parent['children'][$value['name']]);
  486.                         else {
  487.                             $parent['children'][$value['name']] = array();
  488.                         }
  489.                         array_push($parent['aggregKeys']$value['name']);
  490.                     }
  491.                     array_push($parent['children'][$value['name']]$value['value']);
  492.                 else {
  493.                     $parent['children'][$value['name']] &$value['value'];
  494.                     array_push($parent['childrenKeys']$value['name']);
  495.                 }
  496.             else {
  497.                 array_push($parent['children'],$value['value']);
  498.             }
  499.             array_push($this->_valStack$parent);
  500.         }
  501.  
  502.         $this->_depth--;
  503.     }
  504.  
  505.     /**
  506.      * Handler for character data
  507.      *
  508.      * @access private
  509.      * @param  object XML parser object
  510.      * @param  string CDATA
  511.      * @return void 
  512.      */
  513.     function cdataHandler($parser$cdata)
  514.     {
  515.         $this->_dataStack[$this->_depth.= $cdata;
  516.     }
  517. }
  518. ?>

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