length # Example: $columns = array( "field1" => 10, "field2" => 15, "field3" => 7 ); $columns = array( "SEXO" => 1, "CIRCUNS" => 3, "LIBRO" => 3, "INSCRIP" => 3, "CEDULA" => 8, "DIGITO" => 1, "NOMBRE" => 36, "FNACIM" => 8, "ANALF" => 1, "NOVID" => 1, "FINSCRIP" => 8, "NACION" => 15, "PROFESION" => 3, "DIRECCION" => 40 ); # Column Separator $sep = ","; # Field Delimiter $delim = "\""; # utf8 file ? $utf8 = true; # Trim fields (remove empty spaces at begining and end) $trim = true; ########################### CODE ########################### # Generate Columns Names $n_columns = count ($columns); reset($columns); $i = 0; while (list($name, $length) = each($columns)) { echo $delim . $name . $delim; $i++; if ($i < $n_columns) echo $sep; else echo "\n"; } $file = @fopen($filename, "r"); if ( !$file ) die("Error, can't open file: '" . $filename . "'\n"); while ($line = fgets($file)) { if ( trim($line) != "") { $begin = 0; $buffer = ""; # Advance all columns $i = 0; reset($columns); while (list($name, $length) = each($columns)) { # Column counter $i++; # Get values of field $field = substr($line, $begin, $length); # Trim field if ($trim) $field = trim ($field); # Convert Charset if ($utf8) $field = utf8_encode($field); # make field with delimiters $buffer .= $delim . $field . $delim; # check if it's the last field on the record if ($i < $n_columns) $buffer .= $sep; else $buffer .= "\n"; # update begining of next field $begin += $length; } # output the csv line echo $buffer; } } fclose($file); ?>