foreach - Moving CSV file

2

I need to go 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 which is written: 2.98

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

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

In the above code it prints this to 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"" }

Which in this case is all that is on line 1.

    
asked by anonymous 15.08.2017 / 14:51

3 answers

3

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);
}
    
15.08.2017 / 15:16
1

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

So to correct, just change the comma through the semicolon:)

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

Official fgetcsv documentation: php.net/manual/en_US/function.fgetcsv.php

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

    
15.08.2017 / 15:00
1

Manipulation of .csv files can be done easily. There is a package called CSV that you can install via composer . Recently I posted an answer about this issue.

This package transforms the file information into a array that can be easily traversed.

<?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.

    
15.08.2017 / 15:24