Array with a text file

Asked

Viewed 410 times

1

Hello,

I need a method that PHP will read a text file. An example of what the file will contain:

none|link

So when PHP finishes reading the file, it gives an array with the name and link, for example:

<?php
$conteudo = array('nome' => 'link');
?>

I searched the Internet but couldn’t find.

2 answers

5


A solution would be to read the file line by line and add to the array:

   <?php
    $arq = fopen('arquivo.txt', 'r');
    $conteudo = array();
    if( $arq ) {
        while( ( $linha = fgets( $arq ) ) !== false )
        {
            $keyValue = explode( '|', $linha, 2 );
            if( count( $keyValue ) === 2 )
            {
                $key = $keyValue[0];
                $value = $keyValue[1];
                $conteudo[$key] = $value;
            }
        }
        fclose( $arq );
    }
    else
    {
        die('Erro ao abrir arquivo!');
    }
  • Oops! Gave right here, valeuzão!!

4

Run the code below, where "filename.txt" is the name of your file to be read. The array will be stored in the variable $conteudo

$conteudo = array();
$f = fopen("nomedoarquivo.txt", "r");
while ($linha = fgetcsv($f, 0, '|'))
{
    // retira o primeiro elemento do array, retornando-o para a variável $chave
    $chave = array_shift($linha);
    // associa a chave determinada na linha anterior o elemento restante do array
    $conteudo[$chave] = $linha;
}
fclose($f);
var_dump($conteudo);
  • Gave an error here: Warning: fopen() expects at least 2 Parameters, 1 Given in C: xampp htdocs_ teste2.php on line 3 Warning: fgetcsv() expects Parameter 1 to be source, Boolean Given in C: xampp htdocs_ teste2.php on line 4 Warning: fclose() expects Parameter 1 to be Resource, Boolean Given in C: xampp htdocs_ teste2.php on line 11 array(0) { }

  • 1

    Hello, I updated the code by setting the parameter of which file open mode. In this case, read.

  • It worked now, but the friend over there got to me faster, but still, thanks!!

  • 1

    Note that my solution is more compact and elegant. But it is up to you to choose the correct one

Browser other questions tagged

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