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.23 2004/11/06 15:49:52 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.13.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.13';
  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.         $keyAttr = false;
  362.         
  363.         if (is_string($this->options['keyAttribute'])) {
  364.             $keyAttr $this->options['keyAttribute'];
  365.         elseif (is_array($this->options['keyAttribute'])) {
  366.             if (isset($this->options['keyAttribute'][$element])) {
  367.                 $keyAttr $this->options['keyAttribute'][$element];
  368.             elseif (isset($this->options['keyAttribute']['__default'])) {
  369.                 $keyAttr $this->options['keyAttribute']['__default'];
  370.             }
  371.         }
  372.         
  373.         if ($keyAttr !== false && isset($attribs[$keyAttr])) {
  374.             $val['name'$attribs[$keyAttr];
  375.         }
  376.  
  377.         if (isset($attribs[$this->options['classAttribute']])) {
  378.             $val['class'$attribs[$this->options['classAttribute']];
  379.         }
  380.  
  381.         array_push($this->_valStack$val);
  382.     }
  383.  
  384.    /**
  385.     * End element handler for XML parser
  386.     *
  387.     * @access private
  388.     * @param  object XML parser object
  389.     * @param  string 
  390.     * @return void 
  391.     */
  392.     function endHandler($parser$element)
  393.     {
  394.         $value array_pop($this->_valStack);
  395.         $data  trim($this->_dataStack[$this->_depth]);
  396.  
  397.         // adjust type of the value
  398.         switch(strtolower($value['type'])) {
  399.             /*
  400.              * unserialize an object
  401.              */
  402.             case 'object':
  403.                 if(isset($value['class'])) {
  404.                     $classname  $value['class'];
  405.                 else {
  406.                     $classname '';
  407.                 }
  408.                 if (is_array($this->options['tagMap']&& isset($this->options['tagMap'][$classname])) {
  409.                     $classname $this->options['tagMap'][$classname];
  410.                 }
  411.  
  412.                 // instantiate the class
  413.                 if (class_exists($classname)) {
  414.                     $value['value'&new $classname;
  415.                 else {
  416.                     $value['value'&new stdClass;
  417.                 }
  418.                 if ($data !== ''{
  419.                     $value['children'][$this->options['contentName']] $data;
  420.                 }
  421.  
  422.                 // set properties
  423.                 foreach($value['children'as $prop => $propVal{
  424.                     // check whether there is a special method to set this property
  425.                     $setMethod 'set'.$prop;
  426.                     if (method_exists($value['value']$setMethod)) {
  427.                         call_user_func(array(&$value['value']$setMethod)$propVal);
  428.                     else {
  429.                         $value['value']->$prop $propVal;
  430.                     }
  431.                 }
  432.                 //  check for magic function
  433.                 if (method_exists($value['value']'__wakeup')) {
  434.                     $value['value']->__wakeup();
  435.                 }
  436.                 break;
  437.  
  438.             /*
  439.              * unserialize an array
  440.              */
  441.             case 'array':
  442.                 if ($data !== ''{
  443.                     $value['children'][$this->options['contentName']] $data;
  444.                 }
  445.                 if (isset($value['children'])) {
  446.                     $value['value'$value['children'];
  447.                 else {
  448.                     $value['value'= array();
  449.                 }
  450.                 break;
  451.  
  452.             /*
  453.              * unserialize a null value
  454.              */
  455.             case 'null':
  456.                 $data = null;
  457.                 break;
  458.  
  459.             /*
  460.              * unserialize a resource => this is not possible :-(
  461.              */
  462.             case 'resource':
  463.                 $value['value'$data;
  464.                 break;
  465.  
  466.             /*
  467.              * unserialize any scalar value
  468.              */
  469.             default:
  470.                 settype($data$value['type']);
  471.                 $value['value'$data;
  472.                 break;
  473.         }
  474.         $parent array_pop($this->_valStack);
  475.         if ($parent === null{
  476.             $this->_unserializedData &$value['value'];
  477.             $this->_root &$value['name'];
  478.             return true;
  479.         else {
  480.             // parent has to be an array
  481.             if (!isset($parent['children']|| !is_array($parent['children'])) {
  482.                 $parent['children'= array();
  483.                 if (!in_array($parent['type']array('array''object'))) {
  484.                     $parent['type'$this->options['complexType'];
  485.                     if ($this->options['complexType'== 'object'{
  486.                         $parent['class'$parent['name'];
  487.                     }
  488.                 }
  489.             }
  490.  
  491.             if (!empty($value['name'])) {
  492.                 // there already has been a tag with this name
  493.                 if (in_array($value['name']$parent['childrenKeys']|| in_array($value['name']$this->options['forceEnum'])) {
  494.                     // no aggregate has been created for this tag
  495.                     if (!in_array($value['name']$parent['aggregKeys'])) {
  496.                         if (isset($parent['children'][$value['name']])) {
  497.                             $parent['children'][$value['name']] = array($parent['children'][$value['name']]);
  498.                         else {
  499.                             $parent['children'][$value['name']] = array();
  500.                         }
  501.                         array_push($parent['aggregKeys']$value['name']);
  502.                     }
  503.                     array_push($parent['children'][$value['name']]$value['value']);
  504.                 else {
  505.                     $parent['children'][$value['name']] &$value['value'];
  506.                     array_push($parent['childrenKeys']$value['name']);
  507.                 }
  508.             else {
  509.                 array_push($parent['children'],$value['value']);
  510.             }
  511.             array_push($this->_valStack$parent);
  512.         }
  513.  
  514.         $this->_depth--;
  515.     }
  516.  
  517.    /**
  518.     * Handler for character data
  519.     *
  520.     * @access private
  521.     * @param  object XML parser object
  522.     * @param  string CDATA
  523.     * @return void 
  524.     */
  525.     function cdataHandler($parser$cdata)
  526.     {
  527.         $this->_dataStack[$this->_depth.= $cdata;
  528.     }
  529. }
  530. ?>

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