How to fetch data from a CSV file in PHP with different number of rows and columns?

Viewed 22

I am creating a WordPress custom plugin to import product data in Woocommerce by uploading a CSV file. The CSV file contains different kinds of products (simple, variable, grouped, external) with custom attributes and a lot of data. You can look into the CSV file . And here is my code:

<?PHP 

foreach($csv_file as $csv_data){
    //getting csv file name
    $csvFileName = $csv_data["name"];
    $file = fopen($csvFileName, 'r');
    $file_data = fgetcsv($file);
    $fp = file($csvFileName);

    $rows   = array_map('str_getcsv', file($csvFileName));
    $header = array_shift($rows);
    $csv    = array();
    foreach($rows as $row) {
        $csv[] = array_combine($header, $row);
    }
    $assocData = array();

    if( ($handle = fopen( $csvFileName, "r")) !== FALSE) {
        $rowCounter = 0;
        while (($rowData = fgetcsv($handle, 0, ",")) !== FALSE) {
            if( 0 === $rowCounter) {
                $headerRecord = $rowData;
            } else {
                foreach( $rowData as $key => $value) {
                    $assocData[ $rowCounter - 1][ $headerRecord[ $key] ] = $value;  
                }
            }
            $rowCounter++;
        }
        fclose($handle);
    }

//Then iterate $assocData using foreach loop and fetch all keys and values

?>

NOTE : The above code works perfectly for simple product types but throws an error when the above linked CSV file is provided. Here is the error screenshot: enter image description here

MY GOAL : I want to upload a CSV file containing data of mixed product types like 100 simple products, 50 variable products, 20 external products, and 10 grouped products and then upload all products in Woocommerce.

1 Answers

ParseCSV for PHP worked for me. If someone gets into the same situation, they can use this PHP class: https://github.com/parsecsv/parsecsv-for-php It returns CSV file data properly.

After opening the CSV file in PHP and getting file name, I add this PHP from code:

<?PHP 

    $csv = new \ParseCsv\Csv();
    $csv->auto($csvFileName);
    $csv_file_data = $csv->data;

?>

Then, I only needed to iterate the $csv_file_data variable using foreach loop.

Specially thanks for @Deigo referring to that PHP class.

Related