PHP
  Home arrow PHP arrow Page 3 - PHP Datastorage Class (continued)
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

PHP Datastorage Class (continued)
By: Chris Root
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 5
    2005-11-21


    Table of Contents:
  • PHP Datastorage Class (continued)
  • Utility Methods
  • The Output Methods in Depth
  • A Snack for the Road

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    PHP Datastorage Class (continued) - The Output Methods in Depth
    ( Page 3 of 4 )

    Now let's cover some of the output methods that require a separate method. The first one is mode 1, which outputs an array of query strings containing all stored data. In some situations, such as when transferring data to a server you don't control, this will come in handy.

    function to_query_string()
    {
          $keys = array_keys($this->items);
          for($i = 0;$i < count($keys);$i++)
          {
                $ikeys = array_keys($this->items[$i]);
                $q_array[$i] = "";
                for($k = 0;$k < count($ikeys);$k++)
                {
                      $q_array[$i] .= $ikeys[$k]."=".$this->items[$keys[$i]][$ikeys[$k]]."&";
                }
                $q_array[$i] = urlencode(substr($q_array[$i],0,strlen($q_array[$i])-1));
          }
          return $q_array;
    }

    If we have some data stored then we first get all the keys. Nested loops are used to put together a numerical array where each element contains a query string that represents a row in the datastore. Looping through this array to create links in your application takes very little code. Mode 2 also creates query strings, but this time only the keys are included. This can be used to construct links to get specific items out of the datastore. This could be used to retrieve information about individual items in a shopping cart, for instance.

    function id_query()
    {
          $keys = array_keys($this->items);
          $qstr = array();
          for($i = 0;$i < count($keys);$i++)
          {
                $qstr[$i] .= "id=".urlencode($keys[$i]);
          }
          return $qstr
    }

    Next is mode 3, which outputs XSLT. This method accepts a single argument which is the path to a stylesheet, so process the output. A secondary method called get_xml is called first, to convert the information in the datastore to a simple XML format.

    function get_xml($source="blank")
    {
          if($source == "blank")
          {
                $source = $this->items;
          }
          if(is_array($source))
          {
                $keys = array_keys($source);
                $xml_str = "<?xml version=\"1.0\" encoding=\"iso-8859-1\""."?"."><itemgroup>";
                for($i = 0;$i < count($keys);$i++)
                {
                      $xml_str .= "<item id=\"".$keys[$i]."\">";
                      $ikeys = array_keys($this->items[$keys[$i]]);
                      for($k = 0;$k < count($ikeys);$k++)
                      {
                            $xml_str .= "<".$ikeys[$k].">".
                            $this->items[$keys[$i]][$ikeys[$k]].
                            "</".$ikeys[$k].">";
                      }
                      $xml_str .= "</item>";
                }
                $xml_str .= "</itemgroup>";
                return $xml_str;
          }
          else
          {
                $this->err("Input is not an array",1);
          }
    }

    This method allows an optional argument that permits external conversion of an array of the appropriate format to be converted. This potentially includes an array coming from a database using some of the commonly used functions for retrieving records from MySQL or Postgres databases. The XML format that is produced is below.

    <?xml version="1.0" encoding="iso-8859-1?>
    <itemgroup>
    <item>
          <itemcode>255445856</itemcode>
          <model_number>FG405</model_number>
          <description>Colorful widget that makes a lot of noise</description>
          <retail>5.03</retail>
          <discount>4.02</discount>
          <promo>0</promo>
    </item>
    <item>
    <!--second item-->
    </item>
    </itemgroup>

    The code for the from_xslt method is below.

    function from_xslt($file)
    {
          if(file_exists($file))
          {
                if(function_exists("xslt_process"))
                {
                      $resource = fopen($file,"r");
                      $str = fread($resource,filesize($file));
                      $result = null;
                      $xres = $this -> get_xml();
                      $args = array('/_xml' => $xres,'/_xsl' => $this -> $str);
                      xslt_process($resource,'/_xml','/_xsl',$result,$args);
                      xslt_free($resource);
                      return $result;
                }
                else if(function_exists("domxml_xslt_stylesheet_file"))
                {
                      if($xmldoc = domxml_open_mem($this->get_xml()))
                      {
                            $xsldoc  = domxml_xslt_stylesheet_file ($file);
                            $result = $xsldoc->process($xmldoc);
                      }
                      else
                      {echo("error parsing xml document");}
                }
          }
    }

    You will need XSLT support in your PHP distribution to use this method. The choices are the PHP 4x Sablotron XSLT engine or the DOMXML extension. The DOM extension is no longer supported in PHP 5, a new XSL extension based on the libxslt library is used instead. This method could easily be modified if you are using the newest version.

    Mode 4 outputs just the XML format mentioned above.

    The last two output formats are CSV and configuration. The CSV output uses the get_csv method. There is one optional argument to the readout method that is passed on only to this method

    function readout($mode,$file="",$headers=true,$del=":")
    {

    If headers is set to true, the first row in the csv file will be the keys for each item in each row of the datastore. If it is set to false then only the data will be included. This format can be viewed in Microsoft Excel or used as an import format for a database.

    function make_csv($headers,$source="blank")
    {
          if($source = "blank")
          {
                $source = $this->items;
          }
          $head = "";
          $data = "";
          if(is_array($source))
          {
                $keys = array_keys($source);
                for($i = 0;$i < $this->get_count();$i++)
                {
                      $keys2 = array_keys($source[$keys[$i]]);
                      for($j = 0;$j < count($keys2);$j++)
                      {
                            if($i == 0)
                            {
                                  $head .= $keys2[$j].",";
                            }
                            $data .= $source[$keys[$i]][$keys2[$j]].",";
                      }
                      $data .= "\r\n";/**/
                }
                if($headers)
                {
                      $csv_str = $head."\r\n".$data;
                }
                else
                {
                      $csv_str = $data;
                }
                return $csv_str;
          }
          else
          {
                $this-err("input is not an array",1);
          }
    }

    The final output format is the config format. It produces the configuration format mentioned before. The fourth argument of the readout method is the delimiter to be used between the key value pairs.

    function make_config($del)
    {
          $keys = array_keys($this->items);
          $out = "";
          for($i = 0;$i < count($keys);$i++)
          {
                $out .= "#*************\r\n#".$keys[$i]."\r\n#*************";
                $subkeys = array_keys($items[$keys[$i]]);
                for($j = 0;$j < count($subkeys);$j++)
                {
                      $out .= $subkeys[$j].$del.$this->items[$keys[$i]][$subkeys];
                }
          }
          return $out;
    }

    This format can be modified to fit different needs. The datastore itself can be used as a configuration system. The versatility is there if you need it.



     
     
    >>> More PHP Articles          >>> More By Chris Root
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT