I am working on importing a csv of product reviews to my magento.
The csv is in my magento shell folder. I created a product_review.php script inside my shell directory
<?php
require '../app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
ini_set('max_execution_time', 84000);
ini_set('memory_limit', '5120M');
$fp = fopen('final_available_dup.csv', 'r');
//Mage::app()->setCurrentStore(4); //desired store id
while($line = fgetcsv($fp)) {
$review = Mage::getModel('review/review');
$review->setEntityPkValue($line[0]);//previews1.csv
$review->setCreatedAt($line[1]);//previews1.csv
$review->setStatusId($line[2]); //approved
$review->setTitle($line[3]);
$review->setNickname($line[4]);
$review->setDetail($line[5]);
$review->setEntityId($line[6]);
$review->setStoreId(Mage::app()->getStore()->getId());
//$review->setStatusId($line[5]);
$review->setCustomerId($line[7]);//null is for administrator
$review->setReviewsCount($line[8]);//null is for administrator
$review->setReviewId($review->getId());
$review->setStores(array(Mage::app()->getStore()->getId()));
$review->save();
$review->aggregate();
}
?>
and when i run the shell folder and run product_review.php a blank page came which i guess is the correct way.
But when i go into my back end and check i cannot see any reviews.I am not able to which product the review is getting updated.
I don't know is there anything more I should do?
You can use following code for importing product reviews.
My CSV is as following format :
"created_at","Sku","status_id","title","detail","nickname","customer_id","option_id","entity_id"
"2016-04-01 19:42:09","1991474","2","Top","Blij van!!","claes wassenaar","","1:4#3:15#2:9","24582"
So make sure your edit your CSV path in following code and assign proper values to variables.
require_once 'app/Mage.php';
Mage::app();
$fileLocation = "var/import/import_review.csv"; // Set your CSV path here
$fp = fopen($fileLocation, 'r');
$count = 1;
while($data = fgetcsv($fp)){
if($count > 1){
//initiate required variables
$_createdAt = $data[0];
$_sku = $data[1];
$_catalog = Mage::getModel('catalog/product');
$_productId = $_catalog->getIdBySku($_sku);
$_statusId = $data[2];
$_title = $data[3];
$_detail = $data[4];
$_customerId = NULL;
$_nickname = $data[5];
//load magento review model and assign values
$review = Mage::getModel('review/review');
$review->setCreatedAt($_createdAt); //created date and time
$review->setEntityPkValue($_productId);//product id
$review->setStatusId($_statusId); // status id
$review->setTitle($_title); // review title
$review->setDetail($_detail); // review detail
$review->setEntityId(1); // leave it 1
$review->setStoreId(Mage::app()->getStore()->getId()); // store id
$review->setCustomerId($_customerId); //null is for administrator
$review->setNickname($_nickname); //customer nickname
$review->setReviewId($review->getId());//set current review id
$review->setStores(array(Mage::app()->getStore()->getId()));//store id's
$review->save();
$review->aggregate();
//set review ratings
if($data[7]){
$arr_data = explode("#",$data[7]);
if(!empty($arr_data)) {
foreach($arr_data as $each_data) {
$arr_rating = explode(":",$each_data);
if($arr_rating[1] != 0) {
Mage::getModel('rating/rating')
->setRatingId($arr_rating[0])
->setReviewId($review->getId())
->setCustomerId($_customerId)
->addOptionVote($arr_rating[1], $_productId);
}
}
}
$review->aggregate();
}
}
// if($count == 5){
// die("total $count reviews are imported!");
// }
$count++;
}
echo "total $count reviews are imported!";
?>
Related
I am trying to create a simple product programmatically using csv data.
But my product doest not insert in db and admin panel??? Any suggestion pls
Sku,Name,AttributeSetId,CategoryId,Description,Status,TypeId,Price,WebsiteIds,Visibility,UrlKey //title for the csv data
nailPolish,nailpolish,9,2,verybrightproduct,1,simple,200,base,4,nailpolish//csv data
nailRemover,nailremover,9,2,niceproduct,1,simple,200,base,4,nailremover//csv data
<?php
use Magento\Framework\App\Bootstrap;// add bootstrap
include("app/bootstrap.php");
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
function readOptions() //to read csv file
{
$options = array();
$file = 'csv/csvSimpleproduct.csv';
$handle = fopen($file, "r");
$headers = false;
if (empty($handle) === false) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if (!$headers)
$headers[] = $data;
else
$options[] = $data;
}
fclose($handle);
}
return $options;
}
$importProduct = readOptions();
echo '<pre>';
print_r($importProduct);//printing array values
echo '</pre>';
foreach ($importProduct as $importProducts) { //to get single array values
$product = $objectManager->create('\Magento\Catalog\Model\Product');//creating object manager
$product->setSku($importProducts[0]);//to set sku values
$product->setName($importProducts[1]);// to set name of the product
$product->setAttributeSetId($importProducts[2]); //Default attribute set for products
$product->setCategories($importProducts[3]);//
$product->setDescription($importProducts[4]);//to give descriptions
$product->setStatus($importProducts[5]);
$product->setProductType($importProducts[6]);
$product->setPrice($importProducts[7]);// to give price of an product
$product->setWebsiteIds(array(1));//set main website view
$product->setVisibility($importProducts[9]);
$product->setUrlKey($importProducts[10]);//to set url to the product
}
my csv file is:
Sku,Name,AttributeSetId,CategoryId,Description,Status,TypeId,Price,WebsiteIds,Visibility,UrlKey
nailPolish,nailpolish,9,2,verybrightproduct,1,simple,200,base,4,nailpolish
nailRemover,nailremover,9,2,niceproduct,1,simple,200,base,4,nailremover
Maybe something else is wrong, but you need to save your product by product repository
/** #var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$product = $productRepository->save($product);
for now, you do not save product at all
also, it's not a best practice to use object manager directly, use product factory for creating new objects
I know this is duplicate question. But I have tried all the answers which I have found on the https://stackoverflow.com/ .
I think in my case I am inserting and updating data if same date match than record will update if not than it will insert.
Below is my file code:
<?php
if ( isset( $_POST['submit'] ) && $_POST['upload-csv'] == 'upload' ) {
$error = array();
$success = array();
$filename = $_FILES['file']['name'];
$filetype = wp_check_filetype( $filename );
if ( $filetype['ext'] == 'csv' && $filetype['type'] == 'text/csv' ) {
$handle = fopen( $_FILES['file']['tmp_name'], "r" );
$row = 0;
$skip_row_number = array("1");
while ( ($data = fgetcsv( $handle, 1000, "," )) !== FALSE ) {
$data = array_map("utf8_encode", $data);
if ($row > 0)
{
$table_name = $wpdb->prefix . 'prayer';
$ipquery = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `date` = '".$data[0]."'");
$query_res = $wpdb->num_rows;
// Check if same date data
if($query_res >=1){
$updateQuery = "UPDATE `$table_name` SET
`date` = '".$data[0]."',
`first_start` = '".$data[1]."',
`first_end` = '".$data[2]."',
`second_start` = '".$data[3]."',
`second_end` = '".$data[4]."',
`third_start` = '".$data[5]."',
`third_end` = '".$data[6]."',
`forth_start` = '".$data[7]."',
`forth_end` = '".$data[8]."',
`five_start` = '".$data[9]."',
`five_end` = '".$data[10]."',
`done` = '".$data[10]."'
WHERE `$table_name`.`date` = '".$data[0]."';";
$up_res = $wpdb->query($updateQuery);
}else{
$query = "INSERT INTO $table_name (date, first_start, first_end, second_start,
second_end, third_start, third_end, forth_start, forth_end, five_start, five_end, done)
VALUES ('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."','".$data[5]."','".$data[6]."','".$data[7]."','".$data[8]."','".$data[9]."','".$data[10]."','".$data[11]."')";
$insert_res = $wpdb->query($query);
}
}
$row++;
}
fclose( $handle );
$success[] = 'Import done.';
} else {
$error[] = 'Please upload CSV file only';
}
}
?>
I have tried the below answer for skip the header:
Skip the first line of a CSV file
Import CSV, exclude first row
skip first line of fgetcsv method in php
Help me sort out this issue.
ParseCSV is latest and easy way to get data from CSV and you can get control of data from CSV easily.
in which you have to add library file as per proper path
e.g. require_once 'parsecsv.lib.php';
After then it return title and data seperately.
$filename = 'abc.csv'; // path of CSV file or after upload pass temp path of file
$csv = new parseCSV();
$csv->auto($filename);
foreach ($csv->titles as $value):
$getcsvtitle[] = // get header in variable
endforeach;
foreach ($csv->data as $key => $row):
//$getdataasperrow = // get data row wise.
endforeach;
ParseCSV return data in array format after just adding library, so you can easily separate header and other data, and compatible to new line and special character as well as i have been always using it as well.
Please refer below link for further detail as well.
ParseCSV GitHub
I have a product table from where I am checking that quantity for respective product id(s) is valid or not..
this is the code snippet :
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
echo json_encode($array);
exit; /*stop the rest of the code from executing*/
}
}
/*rest of the code outside the loop*/
So here what is happening is it checks the quantity ($quantity_rem) from table of a product id and if that quantity is less than the quantity given ($q), then the script stops and echo the product id..
But I have more that 1 product .. It's not checking the rest since whenever there is a fault it stops and echo out. I want to check all the products and echo out the product id(s) and stop the rest of the script outside the loop..
Help needed!
Thanks.
and please don't talk to me about sql injection because i know it is vulnerable and i will take care of that..
Try this:
$pids = explode(',',$pid); /*in the form of 2,3,4.....*/ /*$pid->product_id*/
$q = explode(',',$q_total); /*in the form of 2,3,4.....*/ /*$q->quantity*/
/*checking start*/
$errors = array();
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
if($quants > $quantity_rem){
$array = array();
$array['errquant'] = 'wrong_quant';
$array['error_pr'] = $ps;
$errors[] = $array;
}
}
echo json_encode($errors);
foreach($pids as $index => $ps){
$quants = $q[$index];
$sql = $stsp->query("SELECT quantity FROM product WHERE id='$ps'");
$row = $sql->fetch(PDO::FETCH_ASSOC);
$quantity_rem = $row['quantity'];
$array = array();
if($quants > $quantity_rem){
$array[$ps]['errquant'] = 'wrong_quant';
// note little change - you will get array with product ids as key
//and qty error assigned to them
}
echo json_encode($array);
exit; /*stop the rest of the code from executing*/
I have csv which contain tracking number, tracking link, carrier code, order number. I am able to set tracking number, carrier code to particular order but not able to set tracking URL for the same order. please suggest me some code snippets or any way to solve this query.
if (($handle = fopen("".$webshopimport_path."\\CSV\\trackandtrace.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE)
{
Mage::init();
$comment = null;
$email = false;
$includeComment = false;
$orderId = '100000065'; //get ordernumber from csv
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
$convertor = Mage::getModel('sales/convert_order');
$shipment = $convertor->toShipment($order);
foreach ($order->getAllItems() as $orderItem)
{
if (!$orderItem->getQtyToShip()) {
continue;
}
if ($orderItem->getIsVirtual()) {
continue;
}
$item = $convertor->itemToShipmentItem($orderItem);
$qty = $orderItem->getQtyToShip();
$item->setQty($qty);
$shipment->addItem($item);
}
$trackdata = array();
$trackdata['carrier_code'] = $data[2]; //get carrier_code from csv
$trackdata['title'] = $data[2]; //get title from csv
$trackdata['number'] = $data[3]; //get track number from csv
$track = Mage::getModel('sales/order_shipment_track')->addData($trackdata);
$shipment->addTrack($track);
Mage::register('current_shipment', $shipment);
$shipment->register();
$shipment->addComment($comment, $email && $includeComment);
$shipment->setEmailSent(true);
$shipment->getOrder()->setIsInProcess(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
$shipment->sendEmail($email, ($includeComment ? $comment : ''));
}
fclose($handle);
$retVar = true;
}
You are not supposed to set any tracking URL for orders because tracking URL are automatically generated with the order tracking number and the shipping service tracking URL structure.
For exemple, UPS tracking URL is : http://wwwapps.ups.com/WebTracking/track?track=yes&trackNums={tracking_number}
I have been trying to export all of our invoices in a specific format for importing into Sage accounting. I have been unable to export via Dataflow as I need to export the customer ID (which strangely is unavailable) and also a couple of static fields to denote tax codes etc…
This has left me with the option of using the API to export the data and write it to a CSV. I have taken an example script I found (sorry can’t remember where in order to credit it...) and made some amendments and have come up with the following:
<?php
$website = 'www.example.com';
$api_login = 'user';
$api_key ='password';
function magento_soap_array($website,$api_login,$api_key,$list_type,$extra_info){
$proxy = new SoapClient('http://'.$website.'/api/soap/?wsdl');
$sessionId = $proxy->login($api_login, $api_key);
$results = $proxy->call($sessionId,$list_type,1);
if($list_type == 'order_invoice.list'){
/*** INVOICES CSV EXPORT START ***/
$filename = "invoices.csv";
$data = "Type,Account Reference,Nominal A/C Ref,Date,Invoice No,Net Amount,Tax Code,Tax Amount\n";
foreach($results as $invoice){
foreach($invoice as $entry => $value){
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
}
}
$type = "SI";
$nominal = "4600";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, $invoice['created_at']);
$invoicedOn = $date->format('d/m/Y');
$invoiceNo = $invoice['increment_id'];
$subtotal = $invoice['base_subtotal'];
$shipping = $invoice['base_shipping_amount'];
$net = $subtotal+$shipping;
$taxCode = "T1";
$taxAmount = $invoice['tax_amount'];
$orderNumber = $invoice['order_id'];
foreach($orders as $order){
if ($order['order_id'] == $orderNumber){
$accRef = $order['customer_id'];
}
}
$data .= "$type,$accRef,$nominal,$invoicedOn,$invoiceNo,$net,$taxCode,$taxAmount\n";
}
file_put_contents($_SERVER['DOCUMENT_ROOT']."/var/export/" . $filename, "$header\n$data");
/*** INVOICES CSV EXPORT END ***/
}else{
echo "nothing to see here";
}/*** GENERIC PAGES END ***/
}/*** END function magento_soap_array ***/
if($_GET['p']=="1")
{
magento_soap_array($website,$api_login,$api_key,'customer.list','Customer List');
}
else if($_GET['p']=="2")
{
magento_soap_array($website,$api_login,$api_key,'order_creditmemo.list','Credit Note List');
}
else if($_GET['p']=="3")
{
magento_soap_array($website,$api_login,$api_key,'sales_order.list','Orders List');
}
else if($_GET['p']=="4")
{
magento_soap_array($website,$api_login,$api_key,'order_invoice.list','Invoice List');
}
?>
This seems to be working fine, however it is VERY slow and I can’t help but think there must be a better, more efficient way of doing it…
Has anybody got any ideas?
Thanks
Marc
i think on put break; would be okey. because only one key with order_id, no need to looping after found order_id key.
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
break;
}
and you can gather all call(s) and call it with multicall as example:
$client = new SoapClient('http://magentohost/soap/api/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'somestuff.method');
$result = $client->call($session, 'somestuff.method', 'arg1');
$result = $client->call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
array('somestuff.method'),
array('somestuff.method', 'arg1'),
array('somestuff.method', array('arg1', 'arg2'))
));
// If you don't need the session anymore
$client->endSession($session);
source