Jump to content

[SOLVED] Php script - Import products by csv


yeye412

Recommended Posts

Hello everyone,

 

i'm facing an issue by using an Import CSV php script (i run this script every 5 hour by cron) that connect user in admin page and import csv file inside certain folder.

Prestashop version: 1.7.6.1

Steps: 

1)   $request->setPost(array("email" => $adminLoginEmail,"passwd" => $adminLoginPass, "submitLogin" => "Connexion")); 
      $request->call($adminUrl."/index.php?controller=AdminLogin");

  2)   $request->call($adminUrl."/index.php?controller=AdminImport");
         list(,$response) = explode("\r\n\r\n", $request->_webpage, 2);
         preg_match("/token=([a-z0-9]+)/", $response, $matches);
        $token = $matches[1];

   3) $request->setPost(array(
                "controller" => "AdminImport",
                "token" => $token,
                  'skip' => '1',
                'csv' => 'prodotti.csv',
                'entity' => '1',
                'separator' => ';',
                'multiple_value_separator' => ',',
                'iso_lang' => 'it',
                'match_ref' => '1',
                'regenerate' => '0',
                'sendemail' => '1',
                "type_value" => array(                                
                  0 => 'reference',
                  1 => 'name',
                  2 => 'price',
                  3 => 'quantity'
                )
        )
    );

4) curl to --> /index.php?controller=AdminImport&token=xxx"

 

All steps return a 200 http status , and i can see token got by admin login but anything was imported in my shop.

Step 4 response is the html content of the admin import page, i think there's a problem on import csv action..

Can anyone help me please?

 

Thanks a lot.

Edited by yeye412 (see edit history)
Link to comment
Share on other sites

Do not use webservice for cron jobs.
Write your own importer and enter your own key in it.
The key is then read and verified via $ _GET.
It's more lines of code, but safe.
There are enough examples in the forums to import CSV products. Just use search.

If you want to use webservice, the ws_key parameter is passed.
You get it in administration and webservice.
Here you create a new key.

Link to comment
Share on other sites

4 hours ago, Guest said:

Do not use webservice for cron jobs.
Write your own importer and enter your own key in it.
The key is then read and verified via $ _GET.
It's more lines of code, but safe.
There are enough examples in the forums to import CSV products. Just use search.

If you want to use webservice, the ws_key parameter is passed.
You get it in administration and webservice.
Here you create a new key.

Hi Tengler, thank you for reply.

I just used search for many days but I didn't found nothing for 1.7 vs.

I didn't understand your solution, if already exist can you share me some existing examples on web ?

Because I know web service solution and it's different , I don't have to login in administration panel to get token but  I've to use generated key in webservice menu (I already use it for export products).


In this case I'm trying to importing by calling import controller action as backoffice import page do, the only difference is the automation.

 

Thanks again for support :)

Link to comment
Share on other sites

Upload a code sample of how to process a CSV file in php.

If I see that you can program in PHP, I will write a piece of code.
If you can't program in PHP, I can't give advice and nobody will give you a solution without showing that you can program.

I'm sorry, but still looking for someone is rude.
The example for Prestashop 1.6 is also valid for Prestashop 1.7.
You do not write if you upload images and categorize products and much more.

I'm sorry, but still looking for someone is rude.
The example for Prestashop 1.6 is also valid for Prestashop 1.7.
You do not write if you upload images and categorize products and much more.

Two years ago I also met this personally and today I write codes one by one.

 

If you know you can't make it, it's better to hire someone to work.

Price varies between $ 20 - $ 30, depending on the complexity of the CSV file.

 

Link to comment
Share on other sites

I forgot to add some details on csv import script.

I'm trying to import only simple products (no combination) without images .

In attach php script.

if (!defined('_PS_ADMIN_DIR_'))
define('_PS_ADMIN_DIR_', __DIR__);
    require_once (_PS_ADMIN_DIR_.'/class.PSRequest.php');
    /* DB Config */
    $shopID = "1";
    $adminUrl = '...';
    $adminLoginEmail = '...';
    $adminLoginPass = '...';

    $request = new PSRequest();
    $request->setCookieFileLocation(__DIR__.'/PScookie.txt');
    $request->setPost(array("email" => $adminLoginEmail,"passwd" => $adminLoginPass, "submitLogin" => "Connexion")); 
    $request->call($adminUrl."/index.php?controller=AdminLogin");

    $request->call($adminUrl."/index.php?controller=AdminImport");
    list(,$response) = explode("\r\n\r\n", $request->_webpage, 2);
    preg_match("/token=([a-z0-9]+)/", $response, $matches);
    $token = $matches[1];

    $request->setPost(array(
                "controller" => "AdminImport",
                "token" => $token,
      	    	'skip' => '1',
				'csv' => 'prodotti.csv',
				'entity' => '1',
				'separator' => ';',
				'multiple_value_separator' => ',',
                'iso_lang' => 'it',
                'match_ref' => '1',
                'regenerate' => '0',
                'sendemail' => '1',
				"type_value" => array(								
				  0 => 'reference',
				  1 => 'name',
                  2 => 'price',
                  3 => 'quantity'
			    )
        )
    );

    $request->call($adminUrl."/index.php?controller=AdminImport&token=".$token);
        $request->call($adminUrl."index.php?ajax=1&action=import&tab=AdminImport&offset=0&limit=5&token=".$token);

        echo "called AdminImport and POST datas...";

//TEST PURPOSE 
//write response output on file
    $file = fopen("importProducts.log", "w");
    fwrite($file, $response);
    $request = null;

?>

 

 

I'm not php programmer and don't know Prestashop project structure, i'm studying php and prestashop for this reason need some help..  
I can understand most of online code,  and can reuse php scripts .. i think problem is that don't know very good php e prestashop, problem it's not money (i can pay anyone for doing this code) i want only support and  do it alone. 

 

If you can help me i'll thank you, if no it's ok .

 

Regards

Edited by yeye412 (see edit history)
  • Like 1
Link to comment
Share on other sites

22 minutes ago, Guest said:

And I am writing to you that I do not know the structure of your csv file.

If you read php script you can understand csv structure :D 

reference;name;price;quantity;    This is csv header.

Link to comment
Share on other sites

There's no description /description short  and i want to import all in main category (Home).. At this moment it's a simple php script , i can add anytime all product attributes.

 

Problem is on import action  by curl now ..

Link to comment
Share on other sites

not tested:

<?php

    include('./config/config.inc.php');
    include('./init.php');
    
    $csv_file = file_get_contents('prodotti.csv');
    $data = explode("\n", $csv_file);
    $data = array_filter(array_map("trim", $data));
    $default_language = Configuration::get('PS_LANG_DEFAULT');
    
    $i = 0;
    foreach ($data as $csv) {
            $i++;
            
            if ($i < 2) {continue;}  // skip csv header
            
            $csv_values = explode(";", $csv);

            $reference = $csv_values[0];
            $name = $csv_values[1];
            $price = $csv_values[2];
            $quantity = $csv_values[3];
            $category = 2;
            $description = '';
            $description_short = '';
            $product_url = Tools::link_rewrite($name);
            $ean13 = '';
            
            $product_exists = Db::getInstance()->getValue("SELECT reference FROM "._DB_PREFIX_."product WHERE reference = '".$reference."'");
            
            if (empty($product_exists)) {
                    $action = 'insert';
                } else {
                    $action = 'update'; 
                    $product_id = Db::getInstance()->getValue("SELECT id_product FROM "._DB_PREFIX_."product WHERE reference = '".$reference."'");
                }
            
            
            if ($action == 'insert') {
                    $product = new Product();
                    $product->reference = $reference;
                    $product->name = [$default_language => $name];
                    $product->price = round($price,6);
                    $product->wholesale_price = '0.000000';
                    $product->quantity = $quantity;
                    $product->link_rewrite = [$default_language => $product_url];
                    $product->id_category = [$category];
                    $product->id_category_default = $category;
                    $product->description = [$default_language => $description];
                    $product->description_short = [$default_language => $description_short];
                    $product->meta_title = [$default_language => $name];
                    $product->meta_description = [$default_language => $name];
                    $product->meta_keywords = [$default_language => $name];
                    $product->id_tax_rules_group = 0;
                    $product->redirect_type = '404';
                    $product->minimal_quantity = 1;
                    $product->show_price = 1;
                    $product->on_sale = 0;
                    $product->online_only = 0;
                    $product->ean13 = $ean13;
                    $product->active = 1;
                    
                    if($product->add()) {
	                       $product->updateCategories($product->id_category);
	                       StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);
                         $tag_list[] = str_replace('-',',',$product_url);
                         Tag::addTags($default_language, $product->id, $tag_list);
                    }
                    
                    $link = new Link();
                    $url = $link->getProductLink($product->id);
                    
                    echo 'inserted product id: '.$product->id.' | product url: <a href="'.$url.'" target="_blank">'.$url.'</a><br />';
                    
              } // end insert
            
            if ($action == 'update') {
                    $product = new Product($product_id);
                    $product->reference = $reference;
                    $product->name = [$default_language => $name];
                    $product->price = round($price,6);
                    $product->wholesale_price = '0.000000';
                    $product->quantity = $quantity;
                    $product->link_rewrite = [$default_language => $product_url];
                    $product->id_category = [$category];
                    $product->id_category_default = $category;
                    $product->description = [$default_language => $description];
                    $product->description_short = [$default_language => $description_short];
                    $product->meta_title = [$default_language => $name];
                    $product->meta_description = [$default_language => $name];
                    $product->meta_keywords = [$default_language => $name];
                    $product->id_tax_rules_group = 0;
                    $product->redirect_type = '404';
                    $product->minimal_quantity = 1;
                    $product->show_price = 1;
                    $product->on_sale = 0;
                    $product->online_only = 0;
                    $product->ean13 = $ean13;
                    $product->active = 1;
                    
                    if($product->update()) {
	                       $product->updateCategories($product->id_category);
	                       StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);
                         $tag_list[] = str_replace('-',',',$product_url);
                         Tag::addTags($default_language, $product->id, $tag_list);
                    }
                    
                    $link = new Link();
                    $url = $link->getProductLink($product->id);
                    
                    echo 'updated product id: '.$product->id.' | product url: <a href="'.$url.'" target="_blank">'.$url.'</a><br />';
                    
              }  // end update
    
        } // end foreach
            
    

 

Edited by Guest
updated script (see edit history)
Link to comment
Share on other sites

20 hours ago, Guest said:

not tested:


<?php

    include('./config/config.inc.php');
    include('./init.php');
    
    $csv_file = file_get_contents('prodotti.csv');
    $data = explode("\n", $csv_file);
    $data = array_filter(array_map("trim", $data));
    $default_language = Configuration::get('PS_LANG_DEFAULT');
    
    $i = 0;
    foreach ($data as $csv) {
            $i++;
            
            if ($i < 2) {continue;}  // skip csv header
            
            $csv_values = explode(";", $csv);

            $reference = $csv_values[0];
            $name = $csv_values[1];
            $price = $csv_values[2];
            $quantity = $csv_values[3];
            $category = 2;
            $description = '';
            $description_short = '';
            $product_url = Tools::link_rewrite($name);
            $ean13 = '';
            
            $product_exists = Db::getInstance()->getValue("SELECT reference FROM "._DB_PREFIX_."product WHERE reference = '".$reference."'");
            
            if (empty($product_exists)) {
                    $action = 'insert';
                } else {
                    $action = 'update'; 
                    $product_id = Db::getInstance()->getValue("SELECT id_product FROM "._DB_PREFIX_."product WHERE reference = '".$reference."'");
                }
            
            
            if ($action == 'insert') {
                    $product = new Product();
                    $product->reference = $reference;
                    $product->name = [$default_language => $name];
                    $product->price = round($price,6);
                    $product->wholesale_price = '0.000000';
                    $product->quantity = $quantity;
                    $product->link_rewrite = [$default_language => $product_url];
                    $product->id_category = [$category];
                    $product->id_category_default = $category;
                    $product->description = [$default_language => $description];
                    $product->description_short = [$default_language => $description_short];
                    $product->meta_title = [$default_language => $name];
                    $product->meta_description = [$default_language => $name];
                    $product->meta_keywords = [$default_language => $name];
                    $product->id_tax_rules_group = 0;
                    $product->redirect_type = '404';
                    $product->minimal_quantity = 1;
                    $product->show_price = 1;
                    $product->on_sale = 0;
                    $product->online_only = 0;
                    $product->ean13 = $ean13;
                    $product->active = 1;
                    
                    if($product->add()) {
	                       $product->updateCategories($product->id_category);
	                       StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);
                         $tag_list[] = str_replace('-',',',$product_url);
                         Tag::addTags($default_language, $product->id, $tag_list);
                    }
                    
                    $link = new Link();
                    $url = $link->getProductLink($product->id);
                    
                    echo 'inserted product id: '.$product->id.' | product url: <a href="'.$url.'" target="_blank">'.$url.'</a><br />';
                    
              } // end insert
            
            if ($action == 'update') {
                    $product = new Product($product_id);
                    $product->reference = $reference;
                    $product->name = [$default_language => $name];
                    $product->price = round($price,6);
                    $product->wholesale_price = '0.000000';
                    $product->quantity = $quantity;
                    $product->link_rewrite = [$default_language => $product_url];
                    $product->id_category = [$category];
                    $product->id_category_default = $category;
                    $product->description = [$default_language => $description];
                    $product->description_short = [$default_language => $description_short];
                    $product->meta_title = [$default_language => $name];
                    $product->meta_description = [$default_language => $name];
                    $product->meta_keywords = [$default_language => $name];
                    $product->id_tax_rules_group = 0;
                    $product->redirect_type = '404';
                    $product->minimal_quantity = 1;
                    $product->show_price = 1;
                    $product->on_sale = 0;
                    $product->online_only = 0;
                    $product->ean13 = $ean13;
                    $product->active = 1;
                    
                    if($product->update()) {
	                       $product->updateCategories($product->id_category);
	                       StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);
                         $tag_list[] = str_replace('-',',',$product_url);
                         Tag::addTags($default_language, $product->id, $tag_list);
                    }
                    
                    $link = new Link();
                    $url = $link->getProductLink($product->id);
                    
                    echo 'updated product id: '.$product->id.' | product url: <a href="'.$url.'" target="_blank">'.$url.'</a><br />';
                    
              }  // end update
    
        } // end foreach
            
    

 

Hi @Guest,

i tested it , first time it doesn't work , i don't know why , but  include('./init.php'); broke the script.

If someone has problems just have to remove init include , because script seems doesn't need init.php for work.

I want to thanks again to Tengler and will set post as SOLVED :) .

 

  • Haha 1
Link to comment
Share on other sites

If you have a script in the Prestashop directory, it says ./
If you create a folder in the main directory it is ./../
If you create a folder in the modules folder, it is ./../../

Dots replace the path from the folder where the file is.

for example, you create a subfolder in the modules folder

./modules/my_folder/my-script.php

The path of the init.php file will also be:

./../../init.php

Look in the ./config/defines.inc.php file.
There you will see how the dots can be replaced.
e.g.
$ currentDir = dirname (___FILE__);
the file path from the sample above would be:
include (realpath ($currentDir. '/../ init.php));

Edited by Guest (see edit history)
Link to comment
Share on other sites

3 hours ago, Guest said:

If you have a script in the Prestashop directory, it says ./
If you create a folder in the main directory it is ./../
If you create a folder in the modules folder, it is ./../../

Dots replace the path from the folder where the file is.

for example, you create a subfolder in the modules folder

./modules/my_folder/my-script.php

The path of the init.php file will also be:

./../../init.php

Look in the ./config/defines.inc.php file.
There you will see how the dots can be replaced.
e.g.
$ currentDir = dirname (___FILE__);
the file path from the sample above would be:
include (realpath ($currentDir. '/../ init.php));

Yes I know directory navigation and I set correctly path.

Why it works with no including init.php?  Maybe script doesn't need it (?) for this reason I commented it at this moment.

Link to comment
Share on other sites

  • 6 months later...
On 4/14/2020 at 1:12 PM, Guest said:

not tested:


<?php

    include('./config/config.inc.php');
    include('./init.php');
    
    $csv_file = file_get_contents('prodotti.csv');
    $data = explode("\n", $csv_file);
    $data = array_filter(array_map("trim", $data));
    $default_language = Configuration::get('PS_LANG_DEFAULT');
    
    $i = 0;
    foreach ($data as $csv) {
            $i++;
            
            if ($i < 2) {continue;}  // skip csv header
            
            $csv_values = explode(";", $csv);

            $reference = $csv_values[0];
            $name = $csv_values[1];
            $price = $csv_values[2];
            $quantity = $csv_values[3];
            $category = 2;
            $description = '';
            $description_short = '';
            $product_url = Tools::link_rewrite($name);
            $ean13 = '';
            
            $product_exists = Db::getInstance()->getValue("SELECT reference FROM "._DB_PREFIX_."product WHERE reference = '".$reference."'");
            
            if (empty($product_exists)) {
                    $action = 'insert';
                } else {
                    $action = 'update'; 
                    $product_id = Db::getInstance()->getValue("SELECT id_product FROM "._DB_PREFIX_."product WHERE reference = '".$reference."'");
                }
            
            
            if ($action == 'insert') {
                    $product = new Product();
                    $product->reference = $reference;
                    $product->name = [$default_language => $name];
                    $product->price = round($price,6);
                    $product->wholesale_price = '0.000000';
                    $product->quantity = $quantity;
                    $product->link_rewrite = [$default_language => $product_url];
                    $product->id_category = [$category];
                    $product->id_category_default = $category;
                    $product->description = [$default_language => $description];
                    $product->description_short = [$default_language => $description_short];
                    $product->meta_title = [$default_language => $name];
                    $product->meta_description = [$default_language => $name];
                    $product->meta_keywords = [$default_language => $name];
                    $product->id_tax_rules_group = 0;
                    $product->redirect_type = '404';
                    $product->minimal_quantity = 1;
                    $product->show_price = 1;
                    $product->on_sale = 0;
                    $product->online_only = 0;
                    $product->ean13 = $ean13;
                    $product->active = 1;
                    
                    if($product->add()) {
	                       $product->updateCategories($product->id_category);
	                       StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);
                         $tag_list[] = str_replace('-',',',$product_url);
                         Tag::addTags($default_language, $product->id, $tag_list);
                    }
                    
                    $link = new Link();
                    $url = $link->getProductLink($product->id);
                    
                    echo 'inserted product id: '.$product->id.' | product url: <a href="'.$url.'" target="_blank">'.$url.'</a><br />';
                    
              } // end insert
            
            if ($action == 'update') {
                    $product = new Product($product_id);
                    $product->reference = $reference;
                    $product->name = [$default_language => $name];
                    $product->price = round($price,6);
                    $product->wholesale_price = '0.000000';
                    $product->quantity = $quantity;
                    $product->link_rewrite = [$default_language => $product_url];
                    $product->id_category = [$category];
                    $product->id_category_default = $category;
                    $product->description = [$default_language => $description];
                    $product->description_short = [$default_language => $description_short];
                    $product->meta_title = [$default_language => $name];
                    $product->meta_description = [$default_language => $name];
                    $product->meta_keywords = [$default_language => $name];
                    $product->id_tax_rules_group = 0;
                    $product->redirect_type = '404';
                    $product->minimal_quantity = 1;
                    $product->show_price = 1;
                    $product->on_sale = 0;
                    $product->online_only = 0;
                    $product->ean13 = $ean13;
                    $product->active = 1;
                    
                    if($product->update()) {
	                       $product->updateCategories($product->id_category);
	                       StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);
                         $tag_list[] = str_replace('-',',',$product_url);
                         Tag::addTags($default_language, $product->id, $tag_list);
                    }
                    
                    $link = new Link();
                    $url = $link->getProductLink($product->id);
                    
                    echo 'updated product id: '.$product->id.' | product url: <a href="'.$url.'" target="_blank">'.$url.'</a><br />';
                    
              }  // end update
    
        } // end foreach
            
    

 

Hi,  if i want import 2 lang how ajust this script?

Link to comment
Share on other sites

????????????????

You must use a ps_product_lang database entry.
I don't know how your language is marked in the CSV file.
Want advice but no information?
Please consider and complete all information about your CSV file.

Link to comment
Share on other sites

  • 2 months later...

Hi,

Is this possible to altered for adding/updating product with combinations?

(each product has 1 combination of 3 options.. eg.. size: one two three)

for each product i will have the base product price on 0.. and alter the price depending the 'size' (+x amount on impact on price with tax of combination)

Link to comment
Share on other sites

  • 7 months later...

Oui.

Je suis d'accord.

But on ps_pack, we can make a unique product thanks to the double key (see image) :

image.png.1b84feea517e48103b901fab7313ee4b.png

 

So it can be possible to import data thanks to csv ?

I just ask how we can do it ?

Because, I know somes of files PHP, that can be edited and can adapt this import. But not all.

 

Sincerelly

Futamiya

Link to comment
Share on other sites

id_product_pack = owner id_product (ps_product)

id_product_item = pack id_product (ps_product)

id_product_attribute_item = pack id_product_attribute (ps_product_attribute)

In order to populate the ps_pack table, you first need to know the id_product that will be composed of the product package. Then you need to know the id_product part of the package and possibly the id_product_attribute.

CSV pack sample:

id_product_pack;id_product_item;id_product_attribute_item;quantity

15;5;19;5

15;7;0;5

15 = owner product

 

Prestashop function:

Pack::addItem($id_product, $id_item, $qty, $id_attribute_item = 0);

 

Link to comment
Share on other sites

  • 10 months later...
On 11/6/2020 at 5:22 PM, neilrodriguez said:

Un consejo para mejorar vuestro coeficiente en SEO: cuando traduzcáis no utilicéis un traductor o modulo (AI), a parte de no entenderse los motores de búsqueda os bajan el coeficiente -> no sois tan fácil de encontrar en Google (p.ej.). Emplead a un nativo (por cada idioma), bien a través de agencia, bien a través de alguna app (p.ej. Fiverr). ¡Saludos!

Link to comment
Share on other sites

On 11/6/2020 at 9:27 AM, Guest said:

????????????????

You must use a ps_product_lang database entry.
I don't know how your language is marked in the CSV file.
Want advice but no information?
Please consider and complete all information about your CSV file.

Thank you so much "Guest"!

Link to comment
Share on other sites

  • 2 weeks later...
On 9/17/2021 at 3:41 PM, Futamiya said:

Hello,

 

Is it possible to edit files php to insert pack product and connect principal product to his product component ?

 

Sincerelly

You could use a cross-selling module. I don't know how good are the ones in the add-ons store. We have our own.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...