Home arrow PHP arrow Page 3 - PHP Datastorage Class (continued)

The Output Methods in Depth - PHP

In the first part of this two-part article, you started to learn about using alternatives to databases for storing data; specifically, we started to work on creating a class that can handle flat files, session variables, and cookies. This second part picks up right where we left off last time.

TABLE OF CONTENTS:
  1. PHP Datastorage Class (continued)
  2. Utility Methods
  3. The Output Methods in Depth
  4. A Snack for the Road
By: Chris Root
Rating: starstarstarstarstar / 5
November 21, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: