How to read txt file and mount php json?

Asked

Viewed 425 times

-1

I need a code to read a file .txt where the first line of the file has to stay inside a array called Cabecalho and the rest of the lines will be within a array with the name Dados, and then I’m gonna use json_encode() to mount a json. But to ride the array I need to break the strings of txt for each value to stay within its particular key.

<?php
$arquivo = fopen('COBST_BGM1_03_070119P_MOV.txt', 'r');

if ($arquivo == false)
    die('Não foi possível abrir o arquivo.');
$lista = fgets($arquivo);

$dadox['Cabecalho'][] = array(
    'codigo_banco' => substr($lista, 0, 3),
    'lote:' => substr($lista, 3, 4),
    'tipo_registro:' => substr($lista, 7, 1),
    'reservado:' => substr($lista, 8, 8),
    'tipo_incricao:' => substr($lista, 16, 1),
    'n_incricao:' => substr($lista, 17, 15),
    'agencia:' => substr($lista, 32, 4),
    'digito_agencia:' => substr($lista, 36, 1),
    'n_conta:' => substr($lista, 37, 9),
    'digito_verificador:' => substr($lista, 46, 1),
    'reservado_2:' => substr($lista, 47, 5),
    'codigo_beneficiario:' => substr($lista, 52, 9),
    'reservado_3:' => substr($lista, 61, 11),
    'nome_empresa:' => substr($lista, 72, 30),
    'nome_banco:' => substr($lista, 102, 30),
    'reservado_4:' => substr($lista, 132, 10),
    'codigo_remessa_retorno:' => substr($lista, 142, 1),
    'data:' => substr($lista, 143, 8),
    'reservado_5:' => substr($lista, 151, 6),
    'n_sequencial:' => substr($lista, 157, 6),
    'n_versao:' => substr($lista, 163, 3),
    'reservado_6:' => substr($lista, 166, 74)
);



header('Content-Type: application/json');

$dados = array(
    $dadox
);


$json_str = json_encode($dados, JSON_PRETTY_PRINT);



echo "$json_str";

fclose($arquivo);
?>

  • 1

    What changed from your previous question to this one? I couldn’t understand.

1 answer

0


If you use the FILE command, each row of your file will be stored in an array. This way, you can separate the contents into two array. According to what I understood, it would look this way:

<?php
$file = file("meu_arquivo_texto.txt");
$total_linhas  = count($file);
$Dados = array();
for($x=0; $x<$total_linhas; $x++) { 
    if ($x==0){
        $Cabecalho = $file[$x];
    } else {
        $Dados[] = $file[$x];
    }
}

$resultados = array($Cabecalho, $Dados);
header("Content-Type: application/json");
$json_str = json_encode($resultados, JSON_PRETTY_PRINT);
echo $json_str;
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.