length # Example: $columns = array( "field1" => 10, "field2" => 15, "field3" => 7 ); $columns = array( "tipo_id" => 1, "rut" => 8, "rut_verificador" => 1, "ano" => 4, "secretaria_admision" => 2, "apellido_paterno" => 25, "apellido_materno" => 25, "nombres" => 25, "nacionalidad" => 1, "sexo" => 1, "local_educacional" => 4, "unidad_educacional" => 2, "codigo_region" => 2, "codigo_provincia" => 3, "egreso_media" => 4, "fecha_nacimiento" => 8, "estado_civil" => 1, "tiene_trabajo" => 1, "horario_trabajo" => 1, "horas_de_trabajo" => 2, "de_proseguir_estudios" => 1, "grupo_familiar" => 2, "cuantos_trabajan_grupo_familiar" => 2, "jefe_familia" => 1, "quien_financia_estudios" => 2, "cuantos_estudian_grupo_familiar" => 6, "ingreso_bruto_familiar" => 1, "cobertura_salud" => 1, "viven_sus_padres" => 1, "educacion_padres" => 4, "situacion_ocupacional" => 2, "tipo_organismo_donde_trabajan" => 2, "ocupacion_principal" => 4, "rama_actividad" => 4, "rut_padre" => 8, "rut_verificador_padre" => 1, "rut_madre" => 8, "rut_verificador_madre" => 1, "calle" => 40, "numero" => 7, "block" => 7, "depto" => 7, "villa" => 40, "codigo_region" => 2, "codigo_provincia" => 3, "codigo_comuna" => 5, "provincia" => 15, "comuna" => 15, "ciudad" => 15, "numero_telefono" => 7, "email" => 60, "folio_ti" => 10 ); # Column Separator $sep = ","; # Field Delimiter $delim = "\""; # utf8 file ? $utf8 = false; # 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"; } if ( !$lines = file ($filename) ) die("Error, can't open file: '" . $filename . "'\n"); foreach ($lines as $line_num => $line) { 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; } } ?>