How do I get a specific column from a .txt file with PHP

1

I have a txr file with several columns but I want to get only a specific value from the first one. So far I've been able to open the file and separate the values from the header.

<?php
error_reporting(0);
// $delimitador = "/[\t]/";

// Abre o Arquvio no Modo r (para leitura)
$arquivo = fopen ('bases-para-teste/10.txt', 'r');
if($arquivo){
    // Lê o conteúdo do arquivo
    $cabecalho = fgets($arquivo, 1024);
    echo $cabecalho.'<br />';
    while(!feof($arquivo))
    {
        //Mostra uma linha do arquivo
        $linha = fgets($arquivo, 1024);
        echo $linha.'<br />';
    }
    // Fecha arquivo aberto
    fclose($arquivo);
}

I'd like to get the column name only. The file is as follows:

Nome    Sobrenome   Cidade
Wesley  Ferreira Costa  São Paulo
Wendel  Ferreira Costa  São Paulo
    
asked by anonymous 26.12.2017 / 13:29

2 answers

2

In case of an SDF or fixed width

SDF is a space-delimited file (and / or fixed columns). In this case, just use substr .

Syntax:

string substr ( string $string , int $inicio[, int $tamanho] )

Applying to your case:

$nome = substr( $linha, 0, 8 );
//                         ^----- largura da coluna
//                      ^-------- posição inicial da coluna

Manual:

  

link


If it is a file separated by tab s or another special character:

In this case, explode resolves. The tab character can be represented by chr( 9 ) in PHP, being 9 the ASCII code of this (same in Unicode).

Syntax:

array explode ( string $delimiter , string $string [, int $limit ] )

Applying to your case:

$itens = explode( chr( 9 ), $linha );
$nome = $itens[0];

Manual:

  

link

    
26.12.2017 / 16:43
2

Just use fgetcsv and to get the first column use $data[0] , you also need to ignore the first line, which represents only the column names, it should look something like this:

$row = 1;

$nomes = array();

$handle = fopen('arquivo.txt', 'rb');

if ($handle)
{
    while (($data = fgetcsv($handle, 1000, "\t")) !== false)
    {
        if ($row === 1) continue; /*ignora a primeira linha*/

        $row++;

        if (isset($data[0])) {
            $nomes[] = $data[0]; //Vai salvando todos nomes na array
        }
    }

    fclose($handle);
} else {
    die('Erro ao ler o arquivo');
}

print_r($nomes);
  

do not use error_reporting(0); , especially in development environment, if errors occur you will not know what you are doing wrong and if it is production environment read this:

     
    
26.12.2017 / 16:40