Undefined offset when opening CSV file in PHP

0

I have a list of products in a CSV file that I'm trying to pass to a database.

This is my code to open the file.

$tmp_archivo = "file/catalogo.csv";
$archivo = fopen($tmp_archivo, "r");
$row = 0;
if($archivo){
    while ($datos = fgetcsv($archivo, ",")){
        echo utf8_encode($datos[0])."-".utf8_encode($datos[1])."-".utf8_encode($datos[2])."-".utf8_encode($datos[3])."-".utf8_encode($datos[4])."-".utf8_encode($datos[5])."-".utf8_encode($datos[6])."-".utf8_encode($datos[7])."-"."<br>";
}
}

But I get the following lines.

100010008-Alambre galvanizado Nº 18-KG--10001-HAWA-Z205-;;;-
100010009-Alambre negro recocido Nº 16-KG-COD.ANT.-10001-HAWA-Z205-GRUPO ART. EXT.;;;-

Notice: Undefined offset: 1 in /var/www/html/Sis_Pecosa/index.php on line 11

Notice: Undefined offset: 2 in /var/www/html/Sis_Pecosa/index.php on line 11

Notice: Undefined offset: 3 in /var/www/html/Sis_Pecosa/index.php on line 11

Notice: Undefined offset: 4 in /var/www/html/Sis_Pecosa/index.php on line 11

Notice: Undefined offset: 5 in /var/www/html/Sis_Pecosa/index.php on line 11

Notice: Undefined offset: 6 in /var/www/html/Sis_Pecosa/index.php on line 11

Notice: Undefined offset: 7 in /var/www/html/Sis_Pecosa/index.php on line 11
100010010,"Alcayata de acero De 2 1/2""",UN,,10001,HAWA,Z205,;;;--------

lines of my CSV file:

100010008,Alambre galvanizado Nº 18,KG,,10001,HAWA,Z205,
100010009,Alambre negro recocido Nº 16,KG,COD.ANT.,10001,HAWA,Z205,GRUPO ART. EXT.
100010010,"Alcayata de acero De 2 1/2""",UN,,10001,HAWA,Z205,

Some lines if you print them normal, others do not, any help?

Thank you.

    
asked by Alf 05.07.2018 в 15:17
source

2 answers

0

It does not find records and it does not fill the array, therefore it does not generate an element and it does not have the indexes that you will then search. Initialize the variable as an array, then count its elements and if this is greater than the index you need then you can then try to access your index of the array, otherwise you will be trying to access an index in an array that does not exist and will generate the error .

    
answered by 05.07.2018 в 15:25
0

I'll leave you a small example:

$result = mysqli_query($con, 'SELECT * FROM usuarios');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

$fp = fopen('mi_archivo.csv', 'w');

foreach ($row as $val) {
    fputcsv($fp, $val);
}

fclose($fp);

the possible outcome of this would be something like this:

row1 val1, row1 val2
row2 val1, row2 val2 

Documentation fputcsv

I recommend you read the documentation

    
answered by 05.07.2018 в 15:26