Read exact columns csv php

0

I'm reading csv this way:

    $handle = fopen($file, "r");
    while ($data = fgetcsv($handle, 1000, ",")) {
        if($row !== 0)
        {
            $dados      = explode(";", $data[0]);
            $VALOR_1        = utf8_encode($dados[1]);
            $VALOR_2        = $dados[2];
            $VALOR_3        = $dados[3];
            $VALOR_4        = $dados[4];
            $VALOR_6        = $dados[11];

                $insert = "
                    INSERT INTO
                        dados
                    VALUES
                    (
                        NULL,
                        '$VALOR_1',
                        '$VALOR_2',
                        '$VALOR_3',
                        '$VALOR_4',
                        '$VALOR_6',
                    )
                ";
                    //$insert_now = mysqli_query($mysqli, $insert);
        }
    }

The first line of the csv contains the title of each column, the csv has several columns, the problem is that the columns are not always positioned in the same place. What I need is to read the csv, and already to let informed the title of the columns to be saved in the bd.

    
asked by anonymous 14.05.2018 / 14:15

1 answer

-3

Try to assign a variable to the column index, hence the positioning of the column is independent ...

Example:

$fieldnames = fgetcsv($handle, 1000, ',');
$idx_dado_5 = array_search("dado_5", $fieldnames);
while ($row = fgetcsv($handle , 4096, ',')) {

        $valor_5 = $row[$idx_dado_5];
$insert = "
                INSERT INTO
                    dados
                VALUES
                (
                    NULL,
                    '$VALOR_1',
                    '$VALOR_2',
                    '$VALOR_3',
                    '$VALOR_4',
                    '$VALOR_5',
                )
            ";
}
    
25.05.2018 / 16:14