foreach - Browsing CSV archive

Asked

Viewed 1,421 times

2

I need to scroll through a CSV file to capture a value and print it on the screen.

Example:

Column "N" line "2", in this case it is cell N2 that is written: 2,98

How to print this N2 cell on the screen? How to get there?

inserir a descrição da imagem aqui

<?php
$h = fopen("produtividade do trabalho.csv","r");
$i = fgetcsv($h, null, ",");
foreach ($i as $indice => $valor) {
  echo var_dump($i);
}
?>

In the code above he prints this for me:

array(1) { [0]=> string(278) "trabalho;"Código do projeto";"Código do item";"Data de início do trabalho real";"Data final do trabalho real";"Nome da linha";"Desempenho";"Disponibilidade";"Eficiência da linha";"Unidades produzidas";"Unidades previstas";"Unidade de medida";"Unidades padrão por hora";"Duração"" }

In which case, that’s all that’s on line 1.

3 answers

4


You need to open csv and go through array.

See this example removed from the PHP site itself with a slight change:

    $row = 1;
if (($handle = fopen("csv.csv", "r")) !== FALSE)
{
    //Passagem pelas linhas
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
    {
        $num = count($data);
        $row++;
        // Passagem pelas colunas
        for ($col = 0; $col < $num; $col++)
        {
            //Printando apenas a coluna 14
            if ($col == 14)
            {
                echo 'Exibindo valor para linha:'.$row.' e para a coluna: '.$data[$col] . "<br />\n";
            }
        }
    }
    fclose($handle);
}
  • Perfect! That’s what I needed! Thank you very much, I’ve been looking for this for a long time, haha. Now I will give an update and implement in my code. Thank you!

  • And like, there in col == 14, it goes through and up to the letter N, right. Now, if I just want to take line 2? And not the whole "N". Because in this perfect example, he gives me everything he has on N. And I need to just pick up line 2

  • You need to make the comparison with the '$Row' tbm, if($Row == 2){ //block }

  • Thank you very much again!

1

In your case, the problem is in the fgetcsv function call. The third parameter is the delimiter, which you are passing the comma (,), but according to your example, this csv is separated by semicolon (;).

So to correct, just exchange the comma for the point-and-comma :)

$i = fgetcsv($h, null, ";");

Official documentation of fgetcsv: php.net/manual/en/Function.fgetcsv.php

To get the N column, just retrieve inside the foreach the position 13 of the variable $value: $value[13]

  • Thank you Diego, I hadn’t noticed! But my problem is still in the air, which is to take a specific cell. This one is taking everything from Line 1, but I want to take Column N from Line 2

  • @Alex_alex_alex In this case, inside the foreach, the variable $value must be an array with the columns, so to get the column N, just count the index of the Array equivalent to this column. Ex: A = 0, B = 1, C = 2, etc. In this case the N must be position 13, and can take the value thus: $value[13]

1

The handling of files .csv can be made easily. There is a package called CSV that you can install via composer. I recently published an answer on this problem.

This package turns the file information into one array which can be easily covered.

<?php
    use League\Csv\Reader;
    require '../vendor/autoload.php';

    $csv = Reader::createFromPath('caminho/arquivo.csv');
    $csv->setDelimiter(';');

    //remove da busca o cabeçalho do arquivo
    $headers = $csv->fetchOne(0);

    //Retorna todos os resultados
    $linhas = $csv->fetchAll();

    //Retorna o valor
    $valor = $linhas[0][13];
?>

Rows and columns start with index 0.

  • $inputCsv->fetchAll(); it should not be $csv->fetchAll(); ?

  • I agree. This is an example of the package itself. I just changed to csv to be more explicit. I thank you for commenting.

Browser other questions tagged

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