<?php
#
# flat.php (c) 2006 Michael Thompson michael@michaelthompson.org
# for the latest info visit http://michaelthompson.org/doc/
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#

# flat, a PHP class for handling delimited key:value pairs in flat files
#
# 'List of books' example 
#
#        field[tab]value
#        + concatenate line to current field
#        # comment follows
#        [newline] a blank line indicates the end of a record
#
#title [tab]The Colour of Magic
#year  [tab]1986
#chars [tab]Rincewind
#+     [tab]Twoflower
#+     [tab]Cohen
#+     [tab]The Luggage
#+     [tab]Lady Luck
#synop [tab]The eighth son of an eighth son of an eighth son is born
#+     [tab]a 'sourcerer', a kind of wizard so powerful that Discworld's
#+     [tab]very existence is threatened.
#link  [tab]http://www...
#[newline]
#
#title [tab]...
#year  [tab]..
#

class flat
{
  var 
$debug;
  var 
$file;

  function 
setDebug($n) { $this->debug $n; }

  function 
flat($file,$debug=0)
  { 
$this->file $file;
    
$this->debug $debug;
  }

  function 
run($callback_fx='',$skip=0,$limit=0)
  {
    if( !
$this->debug $fh=@fopen($this->file,'r');
    else 
$fh fopen($this->file,'r') or die();

    if( 
$fh )
    {
      
$rn 0;
      if( 
$skip>
      {
        while( !
feof($fh) ) 
        {
          
$buff trim(fgets($fh));
          if( empty(
$buff) )
          { 
$rn++;
            if( 
$rn>=$skip ) break;
          }
        }
      }

      
$n=0;
      while( !
feof($fh) ) 
      {
        
$buff trim(fgets($fh));
        if( 
$buff[0]=='#' ) continue;
        if( empty(
$buff) )
        {
          
$rn++;
          if( !empty(
$callback_fx) && is_callable($callback_fx) ) $callback_fx($rn,$arV);
          else
          {
            if( 
$this->debug )
            {
              echo 
"<xmp>$rn\n\n";
              
print_r($arV);
              echo 
"</xmp>\n";
            }
          }
          
$n++;
          if( 
$limit>&& $n>=$limit ) break;
          unset(
$arV);
        }

        
$ar explode("\t",$buff);
        if( 
$ar[0]=='+' $arV["$key"] .= "\n";
        else 
$key trim($ar[0]);

        
$arV["$key"] .= $ar[1];
      }
      
fclose($fh);
    }
  }
}
?>