Conversão de Arquivo TXT em PHP
Publicado por jose claudio em 06/05/2011
[ Hits: 15.734 ]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body { background-color: #EEE; }
label { display: block; float: left; width: 200px; }
fieldset { border: 0px; }
</style>
</head>
<body>
<h1>Conversor de arquivo texto</h1>
<form name="file_input" enctype="multipart/form-data" action="export.php"
method="post">
<?php echo isset($_GET['message']) ? "<h2>{$_GET['message']}</h2>" : ''; ?>
<fieldset>
<label for="file_in">Selecione o arquivo</label>
<input type="file" name="file_in" id="file_in" value=""/>
</fieldset>
<fieldset>
<label for="send_bt"> </label>
<input type="submit" name="send_bt" id="send_bt" value="Converter"/>
</fieldset>
</form>
</body>
</html>
<?php
// Variavel que armazenará as linhas do arquivo a ser gerado
$retorno = array();
// Valida se foi enviado um arquivo pela pagina index.php
if(isset($_FILES['file_in']))
{
// Armazena as informações do arquivo enviado
$file = $_FILES['file_in'];
// Verifica se o arquivo enviado existe fisicamente
if(file_exists($file['tmp_name']))
{
// Inclui os cabeçalhos para forçar o download do arquivo gerado
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Disposition: attachment; filename=\"export-" .
date('Ymdhis') . ".txt\"");
header("Content-Type: application/force-download");
// Abre o arquivo criando um cursor na primeira linha
$fCursor = fopen($file['tmp_name'], 'r');
// Varre o arquivo linha a linha lendo os registros
while(!feof($fCursor))
{
// Pega uma linha do arquivo
$fLine = fgets($fCursor, 4096);
// Transforma a linha em um vetor separando os campos por dois
espações
$fLineArray = explode(';', ereg_replace(' [ ]+', ';',
ereg_replace("(\r|\n)", "", $fLine)));
// Valida se possui a quantidade de campos especificados no
formato do arquivo
if(count($fLineArray) == 6)
{
// Define a data da ligação
$dataAntiga = ereg_replace('[^0-9]', '', $fLineArray[2]);
$novaData = substr($dataAntiga, 2, 2) . substr($dataAntiga,
0, 2) . substr($dataAntiga, 6, 7);
// Define o código do fornecedor
$codigoFornecedor= '00422802'; //CODIGO DA
DIVEO
//$codigoFornecedor= '00006402'; //CODIGO INTELIG
// DEFINE LOCALIDADE PELO RAMAL
/*
- Ramal com dígitos 11 = DF
- Ramal com dígitos 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 e
22 = SP
- Ramal com dígitos 43 = SP
- Ramal com dígitos 98 = RJ
*/
$origem = array();
$origem[11] = 'DF';
$origem[12] = 'SP';$origem[13] = 'SP';$origem[14] =
'SP';$origem[15] = 'SP';$origem[16] = 'SP';
$origem[17] = 'SP';$origem[18] = 'SP';$origem[19] =
'SP';$origem[20] = 'SP';$origem[21] = 'SP';
$origem[22] = 'SP';$origem[43] = 'SP';
$origem[98] = 'RJ';
$dgOrigem = substr($fLineArray[4], 0, 2) * 1;
// MONTA O REGISTRO REFERENTE A LINHA PARA EXPORTAR
NO ARQUIVO
$newLine = array();
$newLine[] = 'R'; //MOEDA DA DESPESA
$newLine[] = $novaData; //DATA DA CHAMADA EM FORMATO
DDMMYY
$newLine[] = substr($fLineArray[0], 0, 5).'-
'.substr($fLineArray[0], 5, 5); // ACCOUNT CODE UTILIZADO
$newLine[] = $fLineArray[3]; // DURACAO DA CHAMADA EM
SEGUNDOS
$newLine[] = 0;
$newLine[] = str_replace('.', ',', $fLineArray[5]); // CUSTO DA
CHAMADA
$newLine[] = 101; // TIPO DE DESPESA
$newLine[] = '-'; // CÓDIGO DO TIMEKEEPER
$newLine[] = $codigoFornecedor; // CÓDIGO DO
FORNECEDOR
$newLine[] = isset($origem[$dgOrigem]) ?
$origem[$dgOrigem] : 'NA'; // LOCALIDADE DE COBRANÇA
$newLine[] = 'Ligação para: ' . substr($fLineArray[1], 0, 17) .
' ,do ramal: ' . $fLineArray[4]; // DESCRIÇÃO DA DESPESA
// insere um novo nó no vetor com as informações já
formatadas para exportação
$retorno[] = implode("\r\n", $newLine);
}
}
// Gera o arquivo incluindo uma linha entre os registros
echo implode("\r\n\r\n", $retorno);
}
else
{
// Exibe mensagem de erro de arquivo não encontrado
header("Location: index.php?
message=Erro+ao+ler+o+arquivo,+verifique+o+arquivo+de+origem");
}
}
else
{
// Exibe mensagem de erro para selecionar um arquivo
header("Location: index.php?message=Selecione+um+arquivo");
}
Configurando proxy/cache Squid com autenticação
Entendendo as permissões de arquivos no Linux
Instalação Zabbix 4.2 no Ubuntu Server LTS 18.04.2
Configurando alias em placa de rede
Lista de discussão de desenvolvedores PHP de Minas Gerais
Gerando Miniaturas de Imagens com PHP
Portabilidade de métodos construtores em PHP
Gerando documentação de projetos PHP com o DocBlox
Nenhum comentário foi encontrado.
Trabalhando Nativamente com Logs no Linux
Jogando Daikatana (Steam) com Patch 1.3 via Luxtorpeda no Linux
LazyDocker – Interface de Usuário em Tempo Real para o Docker
Linux Mint: Zram + Swapfile em Btrfs
O widget do Plasma 6 Área de Notificação
Internet não funciona corretamente no Linux (1)
tentei instalar o steam pelo terminal, agora ele não abre (2)
Após todos esses anos... youtube! (4)









