I have regular Drupal Commerce setup with installed Feeds, Feeds Tamper and Commerce Feeds modules.
Here is tiny piece of the CSV file I'm trying to import:
SKU,Title,Price,Sizes,Model
JKR122/1,Red T-Shirt,44,"42,44,46",JKR122
JKR122/2,Blue T-Shirt,44,"42,44,46",JKR122
Is it possible using Feeds Tamper, to explode "Sizes" column and import each as separate product. Probably it will be needed to append exploded size to SKU.
I'm no pro in Excel, so if it is possible to easily reformat this huge CSV file, please tell me how.
As problem had to be solved today, I wrote PHP-script which reformats my CSV:
I'll leave question opened, in case anuone knows if this can be done by "Drupal-way".
<?php
define('ATTR_SIZE', 'Sizes');
define('ATTR_SKU', 'SKU');
define('IMPORT_FILE', 'import_file.csv');
define('EXPORT_FILE', 'export_file.csv');
define('CSV_DELIMITER', ',');
// Open csv
if(!file_exists(IMPORT_FILE) || !is_readable(IMPORT_FILE))
die('Check file');
$header = NULL;
$all_rows = array();
if (($handle = fopen(IMPORT_FILE, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, CSV_DELIMITER)) !== FALSE) {
if (!$header)
$header = $row;
else
$all_rows[] = array_combine($header, $row);
}
fclose($handle);
}
// Process csv
$new_rows = array();
foreach ($all_rows as $key => $row) {
if (!empty($row[ATTR_SIZE])) {
$original_row = $row;
$sizes = explode(',', $row[ATTR_SIZE]);
foreach ($sizes as $size) {
$trimmed_size = trim($size);
if (!empty($trimmed_size)) {
$row = $original_row;
$row[ATTR_SIZE] = $trimmed_size; // Save size
$row[ATTR_SKU] = $row[ATTR_SKU] . '/' . $trimmed_size; // Modify SKU
$new_rows[] = $row; // Add new row
}
}
}
else {
$new_rows[] = $row;
}
}
// Save csv
$header = NULL;
$handle = fopen(EXPORT_FILE, 'w');
foreach ($new_rows as $fields) {
if (!$header) {
fputcsv($handle, array_keys($fields));
$header = TRUE;
}
fputcsv($handle, $fields);
}
fclose($handle);
Related
Hi I am importing a csv file, where one of the columns is representing the taxonomy term names separated with ; delimiter.
The code I have is the following:
public function save_post($post,$meta,$terms,$thumbnail,$is_update) {
// Separate the post tags from $post array
if (isset($post['post_tags']) && !empty($post['post_tags'])) {
$post_tags = $post['post_tags'];
unset($post['post_tags']);
}
// Special handling of attachments
if (!empty($thumbnail) && $post['post_type'] == 'attachment') {
$post['media_file'] = $thumbnail;
$thumbnail = null;
}
// Add or update the post
if ($is_update) {
$h = RSCSV_Import_Post_Helper::getByID($post['ID']);
$h->update($post);
} else {
$h = RSCSV_Import_Post_Helper::add($post);
}
// Set post tags
if (isset($post_tags)) {
$h->setPostTags($post_tags);
}
// Set meta data
$h->setMeta($meta);
// Set terms
foreach ($terms as $key => $value) {
$h->setObjectTerms($key, $value);
}
// Add thumbnail
if ($thumbnail) {
$h->addThumbnail($thumbnail);
}
return $h;
}
public function setObjectTerms($taxonomy, $terms)
{
$post = $this->getPost();
if ($post instanceof WP_Post) {
wp_set_object_terms($post->ID, $terms, $taxonomy);
} else {
$this->addError('post_is_not_set', __('WP_Post object is not set.', 'really-simple-csv-importer'));
}
}
The $key is the taxanomy ex: Col and the value is the actual name ex: Fiction Books
Any idea why the taxanomy terms are not ticked when the importation is complete?
Without Symfony, this is how I post excel data to database.
// Include PHPExcel_IOFactory
require_once ('../Classes/PHPExcel/IOFactory.php');
$inputFileName = 'abc.xls';
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database of choice here
}
Now with the ExcelBundle, I am stuck. The documentation doesn't help me at all in this task. I've tried every advice given in similar questions and I cant manage to do this.
Creating an object from a file like the example below doesn't work at all:
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject('file.xls');
How to achieve this task?
I worked this out as follows:
Make sure the path Liuggio/ExcelBundle/Controller/FakeController.php exists
Make sure you update the app/config config.yml and routing.yml are updated with the provided files (Liuggio/ExcelBundle/Tests/app)
Assuming that you are updating the product table, Update the FakeController as follows:
<?php
namespace Liuggio\ExcelBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use AppBundle\Entity\Product;
class FakeController extends Controller
{
public function insertAction()
{
$data = [];
$appPath = $this->container->getParameter('kernel.root_dir');
$file = realpath($appPath . '/../web/excelFiles/abc.xls');
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($file);
$sheet = $phpExcelObject->getActiveSheet()->toArray(null, true, true, true);
$em = $this->getDoctrine()->getManager();
$data['sheet'] = $sheet;
//READ EXCEL FILE CONTENT
foreach($sheet as $i=>$row) {
if($i !== 1) {
$product = new Product();
$product->setProductCode($row['A']);
$product->setProductName($row['B']);
$product->setProductRetailPrice($row['C']);
$product->setProductCost($row['D']);
$product->setProductTax($tax);
$product->setCategory($category);
//... and so on
$em->persist($product);
$em->flush();
//redirect appropriately
}
}
$data['obj'] = $phpExcelObject;
return $this->render('excel/read.html.twig', ['data' => $data ] );
}
}
I have this code listing which exports data to an excel file shown here!, I would like to use a loop that does the same thing instead of hard coding it, suggestions!
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load("workbooks/" . $labref . "/" . $labref . ".xlsx");
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()
->setCellValue('I3', $heading)
->setCellValue('I5', 'Standard Preparation For Assay')
->setCellValue('B7', 'Weight')
…………
//Assay Standard Preparation desired
->setCellValue('A8', 'Desired Weight')
->setCellValue('B8', $weight)
->setCellValue('C8', $vf1)
…………………..
//Other values used
->setCellValue('D22', 'Label Claim')
->setCellValue('D23', 'Tabs or Caps Average')
……..
$objPHPExcel->getActiveSheet()->setTitle($heading);
$dir = "workbooks";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("workbooks/" . $labref . "/" . $labref . ".xlsx");
}
}
Try something like this
$data = R::getAll('SELECT * FROM form'); //Im using redbean
$url = // Your url from the root dir -> the folder you wanna save to
$header = array();
$index = 0;
foreach ($data[0] as $key => $value) {
$header[$index] = $key;
$index += 1;
}
try {
$sheet = new PHPExcel();
$sheet->getProperties()->setCreator('Username')
->setLastModifiedBy('Username')
->setTitle('Title');
$sheet->getDefaultStyle()->getAlignment()->setVertical(
PHPExcel_Style_Alignment::VERTICAL_TOP);
$sheet->getDefaultStyle()->getAlignment()->setHorizontal(
PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$sheet->getDefaultStyle()->getFont()->setName('Calibri');
$sheet->getDefaultStyle()->getFont()->setSize(12);
$sheet->setActiveSheetIndex(0);
$activeSheet = $sheet->getActiveSheet();
$colHeaders = $header;
$col = 'B';
$rownum = 2;
foreach ($colHeaders as $h) {
$activeSheet->setCellValue($col . $rownum, $h);
$activeSheet->getStyle($col . $rownum)->getFont()->setBold(true);
$activeSheet->getColumnDimension($col)->setAutoSize(true);
$col++;
}
foreach ($data as $k => $v) {
$col = 'B';
$rownum++;
if ($k != count($data)) {
foreach ($v as $value) {
$activeSheet->setCellValue($col++ . $rownum, $value);
}
} else {
foreach ($v as $value) {
$rownum++;
$activeSheet->setCellValue($col++ . $rownum, $value);
}
}
}
$writer = PHPExcel_IOFactory::createWriter($sheet, 'Excel2007');
// The URL needs to be a absolute path from the root folder to the save folder
// time() makes sure that the file has a uniq name and allso makes it easy to
// see the leatest verson of it.
$saveObj = $url . time() . '';
$writer->save($saveObj);
exit();
} catch (Exception $e) {
$error = $e->getMessage();
// print("<pre>".print_r($error,true)."</pre>");
}
print("<pre>".print_r($error,true)."</pre>");
exit();
I need to print a simple data from database to a particular block, I have used the code given below and got the text out put but it is not located in the block specified(hello_world).
function hello_world_block_view($delta = '') {
$block = array();
if ($delta == 'hello_world') {
$sql = "SELECT Test_name FROM Test_table";
$result = db_query($sql);
$record = $result->fetch();
foreach ($record as $records) {
echo $records;
}
$block['subject'] = t('Hello world Subject');
$block['content'] = t('Need to print database content');
}
return $block;
}
You need to connect variable $records with $block['content']. So it can looks like:
function hello_world_block_view($delta = '') {
$block = array();
if ($delta == 'hello_world') {
$output = '';
$sql = "SELECT Test_name FROM Test_table";
$result = db_query($sql);
$record = $result->fetch();
foreach ($record as $records) {
$output .= $records;
}
$block['subject'] = t('Hello world Subject');
$block['content'] = $output;
}
return $block;
}
I have a site that is using both WordPress and Opencart. The main site is built off of WP and then there is an OC site in a sub-directory.
I would like to bring the session data from OC into the wordpress site so I can have the Wishlist, Shopping Cart, Checkout, Login status and My Account info throughout the site.
Does anyone know what code I can add to WP to bring in this info?
Thanks again in advance,
Matt
There are already many articles regarding module development and export and session building in OpenCart.
Given your existing pages:
yoursite.com/wordpress
yoursite.com/wordpress/page.php (i.e. your page outside the shop),
yoursite.com/products/catalog/controller/common/header.php -and-
yoursite/products/catalog/view/theme/default/template/common/header.tpl
1. Create file headerXYZ.php using the following code and save it to the root directory of your main site (or other location of your choosing outside your OC shop).
<?php
// Config
require_once('shop/config.php');
// VirtualQMOD
require_once('shop/vqmod/vqmod.php');
$vqmod = new VQMod();
// VQMODDED Startup
require_once($vqmod->modCheck(DIR_SYSTEM . 'startup.php'));
// Application Classes
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/customer.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/affiliate.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/currency.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/tax.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/weight.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/length.php'));
require_once($vqmod->modCheck(DIR_SYSTEM . 'library/cart.php'));
$myVar = array();
$myVar = array();
// Registry
$registry = new Registry();
// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);
// Config
$config = new Config();
$registry->set('config', $config);
// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);
// Url
$url = new Url($config->get('config_url'), $config->get('config_use_ssl') ? $config->get('config_ssl') :
$config->get('config_url'));
$registry->set('url', $url);
// Log
$log = new Log($config->get('config_error_filename'));
$registry->set('log', $log);
function error_handler($errno, $errstr, $errfile, $errline) {
global $log, $config;
switch ($errno) {
case E_NOTICE:
case E_USER_NOTICE:
$error = 'Notice';
break;
case E_WARNING:
case E_USER_WARNING:
$error = 'Warning';
break;
case E_ERROR:
case E_USER_ERROR:
$error = 'Fatal Error';
break;
default:
$error = 'Unknown';
break;
}
if ($config->get('config_error_display')) {
echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
}
if ($config->get('config_error_log')) {
$log->write('PHP ' . $error . ': ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
}
return true;
}
// Error Handler
set_error_handler('error_handler');
// Request
$request = new Request();
$registry->set('request', $request);
// Response
$response = new Response();
$response->addHeader('Content-Type: text/html; charset=utf-8');
$response->setCompression($config->get('config_compression'));
$registry->set('response', $response);
// Cache
$cache = new Cache();
$registry->set('cache', $cache);
// Session
$session = new Session();
$registry->set('session', $session);
// Language Detection
$languages = array();
$query = $db->query("SELECT * FROM " . DB_PREFIX . "language");
foreach ($query->rows as $result) {
$languages[$result['code']] = $result;
}
$detect = '';
if (isset($request->server['HTTP_ACCEPT_LANGUAGE']) && ($request->server['HTTP_ACCEPT_LANGUAGE'])) {
$browser_languages = explode(',', $request->server['HTTP_ACCEPT_LANGUAGE']);
foreach ($browser_languages as $browser_language) {
foreach ($languages as $key => $value) {
if ($value['status']) {
$locale = explode(',', $value['locale']);
if (in_array($browser_language, $locale)) {
$detect = $key;
}
}
}
}
}
if (isset($request->get['language']) && array_key_exists($request->get['language'], $languages) &&
$languages[$request->get['language']]['status']) {
$code = $request->get['language'];
} elseif (isset($session->data['language']) && array_key_exists($session->data['language'], $languages)) {
$code = $session->data['language'];
} elseif (isset($request->cookie['language']) && array_key_exists($request->cookie['language'], $languages)) {
$code = $request->cookie['language'];
} elseif ($detect) {
$code = $detect;
} else {
$code = $config->get('config_language');
}
if (!isset($session->data['language']) || $session->data['language'] != $code) {
$session->data['language'] = $code;
}
if (!isset($request->cookie['language']) || $request->cookie['language'] != $code) {
setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
}
$config->set('config_language_id', $languages[$code]['language_id']);
$config->set('config_language', $languages[$code]['code']);
// Language
$language = new Language($languages[$code]['directory']);
$language->load($languages[$code]['filename']);
$registry->set('language', $language);
// Document
$document = new Document();
$registry->set('document', $document);
// Customer
$registry->set('customer', new Customer($registry));
// Affiliate
$affiliate = new Affiliate($registry);
$registry->set('affiliate', $affiliate);
if (isset($request->get['tracking']) && !isset($request->cookie['tracking'])) {
setcookie('tracking', $request->get['tracking'], time() + 3600 * 24 * 1000, '/');
}
// Currency
$registry->set('currency', new Currency($registry));
// Tax
$tax = new Tax($registry);
$registry->set('tax', $tax);
// Weight
$registry->set('weight', new Weight($registry));
// Length
$registry->set('length', new Length($registry));
// Cart
$registry->set('cart', new Cart($registry));
// Front Controller
$controller = new Front($registry);
// Maintenance Mode
$controller->addPreAction(new Action('common/maintenance'));
// SEO URL's
$controller->addPreAction(new Action('common/seo_url'));
// Router
if (isset($request->get['route'])) {
$action = new Action($request->get['route']);
} else {
$action = new Action('common/home');
}
// Dispatch
$controller->dispatch($action, new Action('error/not_found'));
2. Now, include headerXYZ.php in page.php i.e. Place the statement below on line 1 at the very top of page.php
<?php require_once ('headerXYZ.php');?>
3. Finally, right after the opening body tag of your external page.php page add the following list of statements
<?php
require_once('shop/catalog/model/total/sub_total.php');
require_once('shop/catalog/language/english/total/sub_total.php');
require_once('shop/catalog/model/total/reward.php');
require_once('shop/catalog/model/total/shipping.php');
require_once('shop/catalog/model/total/coupon.php');
require_once('shop/catalog/model/total/tax.php');
require_once('shop/catalog/model/total/credit.php');
require_once('shop/catalog/language/english/total/credit.php');
require_once('shop/catalog/model/total/voucher.php');
require_once('shop/catalog/model/total/total.php');
require_once('shop/catalog/language/english/total/total.php');
foreach($myVar as $key=>$value)
{
$$key = $value;
}
require_once('shop/catalog/controller/common/header.php');
require_once('shop/catalog/view/theme/default/template/common/header.tpl');
?>
That's it... You're done! You should now have a fully functional header (with working cart, login, etc.) in your page located outside of your Opencart shop.
SIDE NOTE: You could also just plug the entire code (including the content of headerXYZ.php and the 13 require_once statements) directly into the your external page.
I was looking for something similar, what I did was to write same html/css for footer and header in both systems, after that, I wrote an additional Wordpress plugin to show user and cart info when user is logged in opencart.
https://github.com/saRca/op2wp