Array with a text file

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 the link, for example:

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

I searched the internet but did not find it.

    
asked by anonymous 18.05.2016 / 00:39

2 answers

5

One solution is to read the file line by line and add it 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!');
    }
    
18.05.2016 / 01:18
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);
    
18.05.2016 / 01:18