Question

I have a products csv file containing both updates to current products and new products to be imported. I would like to filter out all existing products from the update file because I need to run the imports and updates separately. I have a second csv with all current products.

I would like to compare them based on the sku field which is the first field in both files and write any rows that don't exist in both files to a new csv so I can run my import without worrying about over-writing any data in my current products.

I am somewhat of a beginner with PHP so specifics and code examples are definitely appreciated!

Was it helpful?

Solution

I'm going to make some assumptions here ... you will have to adapt the solution to work for you.

I'm assuming that the second field in the csv file is something that when compared file over file will indicate that the product was updated, something like a last updated timestamp.

$prodFile = fopen("current-products.csv", "r");

// build a list of all of the sku's in prodFile
$prods = array();
while ($rec = fgetcsv($prodFile)){
    // I am assuming the second field is an updated timestamp
    $prods[$rec[0]] = $rec[1];
}

fclose($prodFile);

$newProdFile = fopen("new-products.csv", "r");
$addFile = fopen("productsToAdd.csv", "w");
$updateFile = fopen("productsToUpdate.csv", "w");

while ($rec = fgetcsv($newProdFile)){
    if (!array_key_exists($rec[0], $prods)){
        fputcsv($addFile, $rec);
    }
    if (array_key_exists($rec[0], $prods) &&
        $prods[$rec[0]] != $rec[1]){
        fputcsv($updateFile, $rec);
    }   
}
fclose($newProductFile);
fclose($addFile);
fclose($updateFile);     
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top