PHP code example of gevman / yii2-excel-import

1. Go to this page and download the library: Download gevman/yii2-excel-import library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gevman / yii2-excel-import example snippets


$uploadedFile = \yii\web\UploadedFile::getInstanceByName('file');

$importer = new \Gevman\Yii2Excel\Importer([
    'filePath' => $uploadedFile->tempName,
    'activeRecord' => Product::class,
    'scenario' => Product::SCENARIO_IMPORT,
    'skipFirstRow' => true,
    'fields' => [
        [
            'attribute' => 'keywords',
            'value' => 1,
        ],
        [
            'attribute' => 'itemTitle',
            'value' => 2,
        ],
        [
            'attribute' => 'marketplaceTitle',
            'value' => 3,
        ],
        [
            'attribute' => 'brand',
            'value' => function ($row) {
                return strval($row[4]);
            },
        ],
        [
            'attribute' => 'category',
            'value' => function ($row) {
                return strval($row[4]);
            },
        ],
        [
            'attribute' => 'mpn',
            'value' => function ($row) {
                return strval($row[6]);
            },
        ],
        [
            'attribute' => 'ean',
            'value' => function ($row) {
                return strval($row[7]);
            },
        ],
        [
            'attribute' => 'targetPrice',
            'value' => 8,
        ],
        [
            'attribute' => 'photos',
            'value' => function ($row) {
                $photos = [];
                foreach (StringHelper::explode(strval($row[11]), ',', true, true) as $photo) {
                    if (filter_var($photo, FILTER_VALIDATE_URL)) {
                        $file = @file_get_contents($photo);
                        if ($file) {
                            $filename = md5($file) . '.jpg';
                            file_put_contents(Yii::getAlias("@webroot/gallery/$filename"), $file);
                            $photos[] = $filename;
                        }
                    } else {
                        $photos[] = $photo;
                    }
                }

                return implode(',', $photos);
            }
        ],
        [
            'attribute' => 'currency',
            'value' => 13,
        ],
    ],
]);

if (!$importer->validate()) {
    foreach($importer->getErrors() as $rowNumber => $errors) {
        echo "$rowNumber errors <br>" . implode('<br>', $errors);
    }
} else {
    $importer->save();
}

$importer->save();

foreach($importer->getErrors() as $rowNumber => $errors) {
    echo "$rowNumber errors <br>" . implode('<br>', $errors);
}