Search code examples
phpcsvfgetcsv

CSV column values as variables in PHP


I have simple csv file:

id | ean


1 | 2342342345234


2 | 3453453454353


I want to have access for this data by variable in foreach loop: $id = 1, $ean = 2342342345234

Is that possible?

<?php
$row = 1;
if (($handle = fopen("upload/products.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
    $num = count($data);
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "<br />\n";
    }
}
fclose($handle);
}
?>

Solution

  • Your delimiter is a pipe, not a comma so change the third parameter of your fgetcsv. You can then assign the values statically if you are using the values in current iteration, or use an array for later storage.

    $row = 1;
    if (($handle = fopen("upload/products.csv", "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 10000, "|")) !== FALSE) {
              $id = $data[0];
              $ean = $data[1];
    

    ...

    or array:

    $row = 1;
    if (($handle = fopen("upload/products.csv", "r")) !== FALSE) {
         while (($data = fgetcsv($handle, 10000, "|")) !== FALSE) {
              $ids[] = $data[0];
              $eans[] = $data[1];
    

    then use the foreach with the key to access appropriate pairings.

    foreach($ids as $key => $id) {
        echo $id . ' ' . $eans[$key];
    }