Read txt file and save to PHP array

Asked

Viewed 2,879 times

0

I have a txt file, where the data is separated by |.

I would like to read and separate the content from within each pair of | at a position of a vector. But it does not print when I put the print_r outside the while.

<?php
    $arquivo = fopen ('arq.txt', 'r');
    $result = array();
    while(!feof($arquivo)){
        $result = explode("|",fgets($arquivo));
    }
    fclose($arquivo);
    print_r($result);
?>

1 answer

1

So, a short explanation of each line so that you can situate yourself in the code itself:

    <?php
    // Aqui você abre e lê o arquivo
    $arquivo = fopen ('arq.txt', 'r');
    // Aqui você está definindo que a variável é um 'array()'
    $result = array();
    // Você agora irá verificar se existe o arquivo e se o código acim o leu (true|false)
    while(!feof($arquivo)){
        // Aqui foi onde você errou, pois seria '$result[]' e não '$result'
        $result[] = explode("|",fgets($arquivo));
    }
    // Fechando a leitura do arquivo
    fclose($arquivo);
    // Postando resultados
    print_r($result);
?>

The code would be clean:

    <?php
    $arquivo = fopen ('arq.txt', 'r');
    $result = array();
    while(!feof($arquivo)){
        $result[] = explode("|",fgets($arquivo));
    }
    fclose($arquivo);
    print_r($result); 
?>

In case, you forgot to set that variable within the while remains a array(), so he won’t pull any results.

  • Hi Rapha! Thank you for helping me, but when I try this code, which you kindly passed me, displays error 500... Could help me??

  • Inside your log shows some specific error?

  • Failed to load Resource: the server responded with a status of 500 (Internal Server Error)

  • Yes, that he displays the 500 Internal Server Error we know, but you saw some error inside the log file?

  • As I’m starting in programming I still don’t know what this log file is about...

  • I edited the code, try now, please!

  • Thank you for trying again Rapha, but still with error 500.

Show 2 more comments

Browser other questions tagged

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