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

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