<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

/**
 * Extract all the data from a file for individuals.
 * @package sigue
 * @author Vladimir Támara.  vtamara@users.sourceforge.net 
 * @since 16-8-2003.  
 * Given to the public domain. 2003.  No warranties. http://structio.sourceforge.net/sigue
 */

class DataInd {
   /** 
   * @var xmlparser
   */
  var $parser;

  /**
   * @var array
   */
  var $data;

  /**
   * Last type read. Empty means no type read.
   * @var string
   */
  var $type;

 /** 
  * @param string $file name of the file to be parsed
  */
  function DataInd($file) {
      $this->data=array();
      $this->parser = xml_parser_create("ISO-8859-1");

      xml_set_object($this->parser, &$this);
      xml_set_element_handler($this->parser, "tag_open", "tag_close");
      xml_set_character_data_handler($this->parser, "cdata");

      $type="";
      if (!($fp = fopen("$file", "r"))) {
	die("El archivo con datos de individuo ".$file." no pudo ser leído");
      }
      while ($data = fread($fp, 4096)) {
          if (!xml_parse($this->parser, $data, feof($fp))) {
	  die(sprintf("XML error: %s en la línea %d, por favor revise ".$file,
		      xml_error_string(xml_get_error_code($this->parser)),
		      xml_get_current_line_number($this->parser)));
	  }
      }
      xml_parser_free($this->parser);
      fclose($fp);
    }

  /**
   * function that process the start of an element
   * @param $parser xml parser
   * @param $name name of the element
   * @param $attrs attributes of the element 
   * @access private 
   */
  function tag_open($parser, $name, $attrs)
    { 
      if (strcmp($name,'DATO')==0) {
	$this->type=$attrs['TIPO'];
        $this->data[$this->type]="";
      }
    }
  
  /**
   * function that process the end of an element
   * @param $parser xml parser
   * @param $name name of the element
   * @access private 
   */
  function tag_close($parser, $name)
    {
	$this->type="";
    }

  /**
   * function that process the content of the element
   * @param $parser xml parser
   * @param $data ASCII data of the element
   * @access private 
   */  
  function cdata($parser, $data) {
        if (isset($this->type) && $this->type!='') {
	    // Al menos con PHP5 en OpenBSD 
	    // los datos llegan por partes (no detecta encoding?).
	    $this->data[$this->type].=$data;
	}
  }  

  /**
   * Function that prints the html code of the data
   */
  function display () 
    {
      foreach ($this->data as $type => $val) {
	  print "<tr><td>$type</td><td>$val</td></tr>\n";
      }
    }

  /**
   * This function returns the association array with the data read.
   */
  function values() 
    {
      return $this->data;
    }  
} // end of class xml

?>
