Read exact csv php columns

Asked

Viewed 503 times

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 csv contains the title of each column, csv has multiple columns, the problem is that the columns are not always positioned in the same location. What I need is to read the csv, and leave already informed the title of the columns to be saved in the comic.

inserir a descrição da imagem aqui

  • Put the example of csv, because apparently the rest is already done. and to better understand your doubt needs some example

  • In the archive csv has a column separator, which in its example is the ;, this isn’t working?

  • You need to identify the columns in the table! also with this table that needs to record results!?

  • But if you’re using fgetcsv so use explodes? No need for this. Tell me, which separator your csv uses, is comma or comma point?

1 answer

-3

Try to assign to a variable the column index, then it is independent the positioning of the same...

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',
                )
            ";
}

Browser other questions tagged

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