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

Documentation generated on Mon, 11 Mar 2019 14:00:16 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.