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

Asked

Viewed 1,448 times

1

I have a txr file with several columns but I want to get only a specific value of the first one. So far I was 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 would like to take only the name column. The file is as follows:

Nome    Sobrenome   Cidade
Wesley  Ferreira Costa  São Paulo
Wendel  Ferreira Costa  São Paulo
  • How is the format of . txt?

  • You mean how the contents are inside him ?

  • yes, it doesn’t need to be the real file, just an example already this good

  • I’ve already updated the post

2 answers

2

Just use the fgetcsv and to catch the first column use $data[0], it is also necessary to ignore the first row, which represents only the names of the columns, 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);

don’t use the 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 take a look at it:

  • appeared only "Array()"

  • @wferreiracosta is because your . txt is with some problem then, add after the $row++; this var_dump($data); and say what comes up.

  • @wferreiracosta do not use the 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 take a look at this: https://answall.com/q/106562/3635

  • @wferreiracosta has how to send me the file bases-para-teste/10.txt?

  • I can not send and business rule, I already solved the problem.

2


In the case of an SDF or fixed width

SDF is a file delimited by spaces (and/or fixed columns). In this case, just use the 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

Handbook:

http://php.net/manual/en/function.substr.php


In the case of a file separated by tabs or other special character:

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

Syntax:

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

Applying to your case:

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

Handbook:

http://php.net/manual/en/function.explode.php

  • Or else "\t" :)

  • 1

    chr(9) was well to style old school of Bacco, @Guilh :)

  • @bfavaretto imagine, incredible as it may seem, I have this vicious too xD

Browser other questions tagged

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