Jump to content
Marcos RJ

Retirar espaços de um arquivo txt com PHP

Recommended Posts

Olá pessoal.

 

Como faço para retirar os espaços de um arquivo txt? Por ex.: Tenho o arquivo abaixo (apenas um trecho, pois o arquivo é grande):

 

10400000         2090183800001990000000000000000000001234204321000000000EMPRESA                       C ECON FEDERAL                          20601201405551100162204000000                    RETORNO-PRODUCAO                  000            
10400011T0100030 20090183800001990000000000000000000001234204321000000000EMPRESA                                                                                                       00001622060120140000000000                          00   
1040001300001T 060000000432100000000   240000000111369979100000000000000002012014000000000008000000010860000000000000000          090000000000000000     

Como faço para que ele fique da seguinte forma (O ex. abaixo é de um outro arquivo):

 

02RETORNO0000000000000000011119999990000000000000000000000000000000000000000104000000000000000201016000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001

O código inicial que tenho é esse:

$arquivo = $_FILES["Arquivo"]["tmp_name"];

$ler = fopen($arquivo,"r");

while(!feof($ler)){

   $linhas = fread($ler,999999);

   $banco = substr($linhas,0,3);
   $lote = substr($linhas,4,7);
   $registro = substr($linhas,8,8);

}
echo "Banco: " .$banco."<br>";
echo "Lote: " .$lote."<br>";
echo "Registro: " .$registro."<br>";

Obrigado

Share this post


Link to post
Share on other sites
13 minutos atrás, washalbano disse:

Olá!
Use preg_replace:
preg_replace('/\s+/', '', $string);
onde $string é o texto de onde o sr. pretende remover os espaços em branco.
http://php.net/manual/pt_BR/function.preg-replace.php

 

Olá washalbano.

 

Certo. Coloco o preg_replace depois do while() e coloco a variável $ler? Porque quando coloco antes, ele fica lendo e não responde.

 

 

Share this post


Link to post
Share on other sites
58 minutos atrás, washalbano disse:

Olá!
Use preg_replace:
preg_replace('/\s+/', '', $string);
onde $string é o texto de onde o sr. pretende remover os espaços em branco.
http://php.net/manual/pt_BR/function.preg-replace.php

 

Olá washalbano.

 

Certo. Coloco o preg_replace depois do while() e coloco a variável $ler? Tentei dessa forma, mas a página fica lendo e não retorna nenhum resultado:

 

$ar = $_FILES["Arquivo"]["tmp_name"];
$arquivo = file_get_contents($ar);
$arquivo = preg_replace('/\s+/', '', $arquivo);

 

 

Share this post


Link to post
Share on other sites

Fiz uma alteração no meu código. Coloquei:

$arquivo = file($_FILES["Arquivo"]["tmp_name"]);
$arquivo = preg_replace('/\s+/', '', $arquivo);

foreach($arquivo as $linhasNum => $linhas) {

              $testes = substr($arquivo[$linhasNum],3,5);

}
echo $testes; // Retorno: Testes: 99999 ( retorna do último array 21 e não do primeiro )

Parece que consegui tirar os espaços, porém quando dou um print_r() na variável $arquivo, ele retorna:

 

Array ( [0] => 104000002090183800001990000000000000000000001234204321000000000EMPRESACECONFEDERAL20601201405551100162204000000RETORNO-PRODUCAO000 [1] => 10400011T010003020090183800001990000000000000000000001234204321000000000EMPRESA0000162206012014000000000000 [2] => 1040001300001T060000000432100000000240000000111369979100000000000000002012014000000000008000000010860000000000000000090000000000000000000000000000125020101 [3] => 1040001300002U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [4] => 1040001300003T060000000432100000000240000000111381979100000000000000005012014000000000008000000033170000000000000000090000000000000000000000000000125020101 [5] => 1040001300004U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [6] => 1040001300005T060000000432100000000240000000111378897100000000000000010012014000000000008000000011920000000000000000090000000000000000000000000000125020101 [7] => 1040001300006U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [8] => 1040001300007T060000000432100000000240000000111371256100000000000000010012014000000000008000000011920000000000000000090000000000000000000000000000125020101 [9] => 1040001300008U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [10] => 1040001300009T060000000432100000000240000000000222473100000000000000015012014000000000008000000002700000000000000000090000000000000000000000000000125020101 [11] => 1040001300010U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [12] => 1040001300011T060000000432100000000240000000111369162100000000000000010012014000000000008000000031280000000000000000090000000000000000000000000000125020101 [13] => 1040001300012U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [14] => 1040001300013T060000000432100000000240000000111368980100000000000000010012014000000000008000000036620000000000000000090000000000000000000000000000125020101 [15] => 1040001300014U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [16] => 1040001300015T060000000432100000000240000000000319990100000000000000010012014000000000048000000011920000000000000000090000000000000000000000000000125020101 [17] => 1040001300016U06000000000000000000000000006000000000000000000000000000000000000000000042000000000000042000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [18] => 1040001300017T060000000432100000000240000000000305727100000000000000010012014000000000008000237017950000000000000000090000000000000000000000000000270040101 [19] => 1040001300018U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000 [20] => 1040001500002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 [21] => 10499999000001000022 )

E quando dou o print_r() na variável $arquivo[$linhasNum], o retorno é esse:

 

104000002090183800001990000000000000000000001234204321000000000EMPRESACECONFEDERAL20601201405551100162204000000RETORNO-PRODUCAO000
10400011T010003020090183800001990000000000000000000001234204321000000000EMPRESA0000162206012014000000000000
1040001300001T060000000432100000000240000000111369979100000000000000002012014000000000008000000010860000000000000000090000000000000000000000000000125020101
1040001300002U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300003T060000000432100000000240000000111381979100000000000000005012014000000000008000000033170000000000000000090000000000000000000000000000125020101
1040001300004U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300005T060000000432100000000240000000111378897100000000000000010012014000000000008000000011920000000000000000090000000000000000000000000000125020101
1040001300006U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300007T060000000432100000000240000000111371256100000000000000010012014000000000008000000011920000000000000000090000000000000000000000000000125020101
1040001300008U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300009T060000000432100000000240000000000222473100000000000000015012014000000000008000000002700000000000000000090000000000000000000000000000125020101
1040001300010U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300011T060000000432100000000240000000111369162100000000000000010012014000000000008000000031280000000000000000090000000000000000000000000000125020101
1040001300012U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300013T060000000432100000000240000000111368980100000000000000010012014000000000008000000036620000000000000000090000000000000000000000000000125020101
1040001300014U06000000000000000000000000000000000000000000000000000000000000000000000008000000000000008000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300015T060000000432100000000240000000000319990100000000000000010012014000000000048000000011920000000000000000090000000000000000000000000000125020101
1040001300016U06000000000000000000000000006000000000000000000000000000000000000000000042000000000000042000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001300017T060000000432100000000240000000000305727100000000000000010012014000000000008000237017950000000000000000090000000000000000000000000000270040101
1040001300018U06000000000000000000000000001000000000000000000000000000000000000000000007000000000000007000000000000000000000000000000000060120140701201400000701201400000000000000000000000000000000000000000000000000000000000000000000
1040001500002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
10499999000001000022

 

Share this post


Link to post
Share on other sites

Olá!

Use o preg_replace dentro do foreach

Na variável $linha

Aparentemente a variável  $arquivo é do tipo array

E pra remover espaços em branco, o preg_replace espera uma variável do tipo string

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By Keber_Crato
      Boa noite galera!!  estou com dificuldades em conseguir o somatório de de dois campos de uma tabela e o somatório de um campo de outra tabela,
      segue assim:
      Tenho uma tabela chamada CID_TITULAR  e outra CID_COMPOSICAO. a tabela CID_TITULAR recebe os cadastro de um programa social e a tabela CID_COMPOSICAO o cadastros dos dependentes (filhos, parentes) TITULAR_COD = COMPOSICAO_COD_TITULAR (chave de ligação)
      tenho dois campos na CID_TITULAR de valores, são eles: TITULAR_RENDA e TITULAR_RENDA_MENSAL e na outra tabela CID_COMPOSICAO tenho um campo de valor COMPOSICAO_RENDA
      estão povoado assim:
       
      Na tabela CID_TITULAR nos campos TITULAR_RENDA (R$ 10.00) e TITULAR_RENDA_MENSAL (R$ 10.00) e na tabela CID_COMPOSICAO no campo COMPOSICAO_RENDA tenho 3 registros com os valores R$ 300.00, R$ 200.00 e R$ 100.00
      GOSTARIA QUE A SELEÇÃO FOSSE O VALOR DOS DOIS CAMPOS DA TABELA CID_TITULAR + O CAMPO DA OUTRA TABELA CID_COMPOSICAO
       
      NO CASO O SOMATÓRIO CORRETO SERIA R$ 620,00
      10,00 no campo TITULAR_RENDA
      10,00 no campo TITULAR_RENDA_MENSAL
      300,00 NO 1º REGISTRO no campo COMPOSICAO_RENDA
      200,00 NO 2º REGISTRO no campo COMPOSICAO_RENDA
      100,00 NO 3º REGISTRO no campo COMPOSICAO_RENDA
       
      TOTALIZANDO R$ 620,00
      O PROBLEMA É:
      Quando faço a seleção com inner join a resposta é R$ 660,00 e não 620,00. a seleção triplica o valor da primeira tabela devido ter três registros na tabela CID_COMPOSICAO
       
      TABELA CID_TITULAR
      CREATE TABLE `cid_titular` (
        `titular_cod` int(11) NOT NULL AUTO_INCREMENT,
        `titular_renda` float(10,2) DEFAULT NULL,
        `titular_renda_mensal` float(10,2) DEFAULT NULL,
        PRIMARY KEY (`titular_cod`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
       
      TABELA CID_COMPOSICAO
      CREATE TABLE `cid_composicao` (
        `composicao_cod` int(11) NOT NULL AUTO_INCREMENT,
        `composicao_cod_titular` int(11) DEFAULT NULL,
        `composicao_renda` float(10,2) DEFAULT NULL,
        PRIMARY KEY (`composicao_cod`)
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
       
       
      GOSTARIA MUITO DE AJUDA GALERA. OBRIGADO!!!!
       

    • By malufla79
      Boa tarde, estou com probleminha no phpmailer, o código abaixo funciona corretamente quando consigo enviar para um único e-mail, mas quando coloco a opção todos, ele só manda apenas para primeiro e-mail e não apresenta nenhum erro. Poderia me dar uma ajudinha? Obrigada
       
      Controle
      if ($_POST['filtro'] == 'todos') { // essa consulta pego a lista de e-mails cadastrado no meu banco de dados $usuarios->consultar("select * from mala_email"); $linha = $usuarios->Linha; $rs = $usuarios->Result; } if ($_POST['filtro'] == 'todos') { for ($i=0; $i<$linha; $i++) { $email = $rs[$i]['email']; $mensagem = $_POST['editor']; $util->EnviarEmaiLivre($email, utf8_decode($_POST['assunto']), $mensagem); } } else { $mensagem = $_POST['editor']; $util->EnviarEmaiLivre($_POST['email'], utf8_decode($_POST['assunto']), $mensagem); } Função
      function EnviarEmaiLivre($email, $assunto, $mensagem) { date_default_timezone_set('Etc/UTC'); require 'phpmailer/PHPMailerAutoload.php'; $hostSmtp = "mail.domino.com.br"; $smtpUser = "email@email.com.br"; $senhaSmtp = "********"; $mensagem = ' <p><img src="http://www.dominio.com.br/images/logodolugar.png" alt="Logo do Lugar" width="550"></p> '.$mensagem; //Create a new PHPMailer instance $mail = new PHPMailer; //Tell PHPMailer to use SMTP $mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 0; //Ask for HTML-friendly debug output $mail->Debugoutput = 'html'; //Set the hostname of the mail server $mail->Host = $hostSmtp; // use // if your network does not support SMTP over IPv6 //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission $mail->Port = 587; //Set the encryption system to use - ssl (deprecated) or tls $mail->SMTPSecure = 'tsl'; //Whether to use SMTP authentication $mail->SMTPAuth = true; //Username to use for SMTP authentication - use full email address for gmail $mail->Username = $smtpUser; //Password to use for SMTP authentication $mail->Password = $senhaSmtp; //Set who the message is to be sent from $mail->setFrom('email@email.com.br', 'E-mail do Lugar'); //Set who the message is to be sent to $mail->addAddress($email); //Set the subject line $mail->Subject = $assunto; //Replace the plain text body with one created manually $mail->Body = $mensagem; $mail->isHTML(true); if ($conteudoArquivo != '' && $arquivo != '') { //Attach an image file $mail->addAttachment('phpmailer/images/phpmailer_mini.png'); //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body $mail->msgHTML(file_get_contents('contents.html'), dirname(__FILE__)); } if (!$mail->send()) { $retorno = false; } else { $retorno = true; } }  
       
    • By Leandro Volanick
      Boa tarde pessoal.
       
      Gostaria de uma ajuda em uma consulta sql, onde quero agrupar os todos produtos comprados pelo mesmo CPF, dentro de uma array. 
       
      Segue o que estou usando:
      $data=mysqli_query($mysqli, "SELECT xml.id, xml.xProd as produto, prod.id as iddoproduto, GROUP_CONCAT( prod.xProd ) FROM produtos AS prod LEFT JOIN xml as xml ON xml.xProd = prod.xProd GROUP BY xml.CPFdest"); while($info=mysqli_fetch_array($data)) echo '['.$info['iddoproduto'].'],'; No momento, o codigo está trazendo apenas 1 produto, quero que ele printe todos produtos que o CPFdest já comprou.
       
       
    • By Vítor Gonçalves
      Boa Tarde, gostaria se alguém poderia me ajudar!
      tenho um sistema desktop que é validado a cada 6 meses, quando termina essa validade ele pedi para renovar!
      - desejo criar um script em PHP  com a seguinte função:
      -pegar a senha gerada no sistema e enviar para o servidor web( hostinger server-sql) via php
      - o servidor gera e mostra uma contra senha  para ser copiada de volta.
      - ao colar a contra senha no campo "nova licença" no meu programa, ele compara com a que tá no banco de dados na hostinger se bate a mesma e libera o uso.
       
      - já vi isso em outro sistema mas não tive acesso aos scripts para ver como funciona.
    • By Anonicah
      Olá preciso de ajuda com esse exercício. Montei até a parte de formulário + validação de javascrip no dreamweaver mas buguei com o resto. O que eu fiz:
       

      <html>
      <head>
      <title> Formulário CPF validado com Java Script </title>
          
          <script language="javascript" type="text/javascript">
      function validar() {
      var cpf = form1.cpf.value;
          
      if (cpf == "") {
      alert('Preencha o campo com seu cpf');
      form1.cpf.focus();
      return false;
      }
          
      }
      </script>
          
          
      </head>
      <body>
      <form name="form1" action="enviar.php" method="post">
      CPF:
      <input name="cpf" type="text"><br /><br />
      <input type="submit"  onclick="return validar()">
      </form>
      </body>
      </html>
       
       
      EXERCÍCIO
      Criar um formulário simples em html com um único campo CPF;
      Fazer uma validação em javascript antes de fazer o post;
      Consumir o WS https://bi.vidaclass.com.br/utils para consultar informações do CPF enviado pelo form;
      Do retorno obtido exibir na tela:
      Nome, email, telefone
      Se tem compra em saude: Sim | Não
      Quantas compras: (5) ex.
      Se tem farma: Sim | Não
      Se tem dependente: Sim | Não
      Qtd. de dependentes: (2) ex.

      Obtem o token para consumir os endpoints;
      https://bi.vidaclass.com.br/auth
      {
          "company_id": 1,
          "username": "webmaster@vidaclass.com.br",
          "password": "Teste20170705"
      }
      Endpoint para consultar o CPF
      https://bi.vidaclass.com.br/utils
      {
          "action": 4,
          "key": {
              "cpf": 25383193820
          }
      }
×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.