Conversão de Arquivo TXT em PHP
Publicado por jose claudio em 06/05/2011
[ Hits: 15.604 ]
<!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
Configurando IP estático em uma placa de rede
Configuração do SARG em 20 minutos
Instalação Zabbix 4.2 no Ubuntu Server LTS 18.04.2
Configurando alias em placa de rede
Colocando o "bcompiler" pra funcionar no PHP5
Escovando bits em PHP - operações bitwise sobre grupos e permissões
Nasce site sobre Zend Framework
Livro sobre Joomla - Criando Componentes Comerciais
Como instalar o PHP5 no Debian 9 Stretch
Nenhum comentário foi encontrado.
Monitorando o Preço do Bitcoin ou sua Cripto Favorita em Tempo Real com um Widget Flutuante
IA Turbina o Desktop Linux enquanto distros renovam forças
Como extrair chaves TOTP 2FA a partir de QRCODE (Google Authenticator)
Ativando e usando "zoom" no ambiente Cinnamon
Vídeo Nostálgico de Instalação do Conectiva Linux 9
Como realizar um ataque de força bruta para desobrir senhas?
Eu queria adicionar a incon do wifi e deixa transparente no fluxbox no... (2)
Scripts ou binários [RESOLVIDO] (5)
Perfil criado no samba ad dc não loga no Windows 10 e 11 (12)









