SellerTaobaoImport.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  1. <?php
  2. namespace app\home\controller;
  3. use think\facade\View;
  4. use think\facade\Lang;
  5. use think\facade\Db;
  6. /**
  7. *
  8. *
  9. * ----------------------------------------------------------------------------
  10. *
  11. * 控制器
  12. */
  13. class SellerTaobaoImport extends BaseSeller
  14. {
  15. public function initialize()
  16. {
  17. parent::initialize();
  18. error_reporting(E_ERROR | E_WARNING);
  19. Lang::load(base_path() . 'home/lang/' . config('lang.default_lang') . '/sellergoodsadd.lang.php');
  20. }
  21. public function index()
  22. {
  23. if (!request()->isPost()) {
  24. /**
  25. * 获取商品分类
  26. */
  27. $gc = model('goodsclass');
  28. $gc_list = $gc->getGoodsClass(session('store_id'));
  29. View::assign('gc_list', $gc_list);
  30. /**
  31. * 获取店铺商品分类
  32. */
  33. $model_store_class = model('storegoodsclass');
  34. $store_goods_class = $model_store_class->getClassTree(array('store_id' => session('store_id'), 'storegc_state' => '1'));
  35. View::assign('store_goods_class', $store_goods_class);
  36. if (input('get.step') != '') {
  37. View::assign('step', input('get.step'));
  38. } else {
  39. View::assign('step', '1');
  40. }
  41. } else {
  42. $file = $_FILES['csv'];
  43. /**
  44. * 上传文件存在判断
  45. */
  46. if (empty($file['name'])) {
  47. $this->error(lang('store_goods_import_choose_file'));
  48. }
  49. /**
  50. * 文件来源判定
  51. */
  52. if (!is_uploaded_file($file['tmp_name'])) {
  53. $this->error(lang('store_goods_import_unknown_file'));
  54. }
  55. /**
  56. * 文件类型判定
  57. */
  58. $file_name_array = explode('.', $file['name']);
  59. if ($file_name_array[count($file_name_array) - 1] != 'csv') {
  60. $this->error(lang('store_goods_import_wrong_type') . $file_name_array[count($file_name_array) - 1]);
  61. }
  62. /**
  63. * 文件大小判定
  64. */
  65. if ($file['size'] > intval(ini_get('upload_max_filesize')) * 1024 * 1024) {
  66. $this->error(lang('store_goods_import_size_limit'));
  67. }
  68. /**
  69. * 商品分类判定
  70. */
  71. if (empty(input('post.gc_id'))) {
  72. $this->error(lang('store_goods_import_wrong_class'));
  73. }
  74. $gc = model('goodsclass');
  75. $gc_row = $gc->getGoodsClassLineForTag(input('post.gc_id'));
  76. if (!is_array($gc_row) or count($gc_row) == 0) {
  77. $this->error(lang('store_goods_import_wrong_class1'));
  78. }
  79. $gc_sub_list = $gc->getGoodsClassList(array('gc_parent_id' => intval(input('post.gc_id'))));
  80. if (is_array($gc_sub_list) and count($gc_sub_list) > 0) {
  81. $this->error(lang('store_goods_import_wrong_class2'));
  82. }
  83. /**
  84. * 店铺商品分类判定
  85. */
  86. $sgcate_ids = array();
  87. $stc = model('storegoodsclass');
  88. if (is_array(input('post.sgcate_id/a')) and count(input('post.sgcate_id/a')) > 0) {
  89. foreach (input('post.sgcate_id/a') as $sgcate_id) {
  90. if (!in_array($sgcate_id, $sgcate_ids)) {
  91. $stc_row = $stc->getStoregoodsclassInfo(array('storegc_id' => $sgcate_id));
  92. if (is_array($stc_row) and count($stc_row) > 0) {
  93. $sgcate_ids[] = $sgcate_id;
  94. }
  95. }
  96. }
  97. }
  98. /**
  99. * 上传文件的字符编码转换
  100. */
  101. $csv_string = $this->unicodeToUtf8(file_get_contents($file['tmp_name']));
  102. /* 兼容淘宝助理5 start */
  103. $csv_array = explode("\tsyncStatus", $csv_string, 2);
  104. if (count($csv_array) == 2) {
  105. $csv_string = $csv_array[1];
  106. }
  107. /* 兼容淘宝助理5 end */
  108. /**
  109. * 将文件转换为二维数组形式的商品数据
  110. */
  111. $records = $this->parse_taobao_csv($csv_string);
  112. if ($records === false) {
  113. $this->error(lang('store_goods_import_wrong_column'));
  114. }
  115. /**
  116. * 转码
  117. */
  118. if (strtoupper(CHARSET) == 'GBK') {
  119. $records = $this->getGBK($records);
  120. }
  121. $model_goodsclass = model('goodsclass');
  122. $model_store_goods = model('goods');
  123. // 商品数量
  124. $goods_num = $model_store_goods->getGoodsCommonCount(array('store_id' => session('store_id')));
  125. /**
  126. * 商品数,空间使用,使用期限判断
  127. */
  128. $model_store = model('store');
  129. $store_info = $model_store->getStoreInfo(array('store_id' => session('store_id')));
  130. $model_store_grade = model('storegrade');
  131. $store_grade = $model_store_grade->getOneStoregrade($store_info['grade_id']);
  132. /* 商品数判断 */
  133. $remain_num = -1;
  134. if (intval($store_grade['sg_goods_limit']) != 0) {
  135. if ($goods_num >= $store_grade['sg_goods_limit']) {
  136. $this->error(lang('store_goods_index_goods_limit') . $store_grade['sg_goods_limit'] . lang('store_goods_index_goods_limit1'));
  137. }
  138. $remain_num = $store_grade['sg_goods_limit'] - $goods_num;
  139. }
  140. /* 使用期限判断 */
  141. if (intval($store_info['store_end_time']) != 0) {
  142. if (TIMESTAMP >= $store_info['store_end_time']) {
  143. $this->error(lang('store_goods_index_time_limit'));
  144. }
  145. }
  146. /**
  147. * 循环添加数据
  148. */
  149. $str = '';
  150. if (is_array($records) and count($records) > 0) {
  151. foreach ($records as $k => $record) {
  152. if ($remain_num > 0 and $k >= $remain_num) {
  153. $this->error(lang('store_goods_index_goods_limit') . $store_grade['sg_goods_limit'] . lang('store_goods_index_goods_limit1') . lang('store_goods_import_end') . (count($records) - $remain_num) . lang('store_goods_import_products_no_import'), (string)url('SellerTaobaoImport/index', ['step' => 4]));
  154. }
  155. if (is_array($record['goods_image'])) {
  156. $str .= implode(',', $record['goods_image']);
  157. $str .= "\r\n";
  158. } else {
  159. $str .= $record['goods_image'] . "\r\n";
  160. }
  161. //file_put_contents('image.txt',$str,FILE_APPEND);
  162. $pic_array = $this->get_goods_image($record['goods_image']);
  163. if (empty($record['goods_name']))
  164. continue;
  165. $param = array();
  166. $param['goods_name'] = $record['goods_name'];
  167. $param['gc_id'] = intval(input('post.gc_id'));
  168. $param['gc_id_1'] = intval(input('post.cls_1'));
  169. $param['gc_id_2'] = intval(input('post.cls_2'));
  170. $param['gc_id_3'] = intval(input('post.cls_3'));
  171. $param['gc_name'] = input('post.cate_name');
  172. $param['spec_name'] = 'N;';
  173. $param['spec_value'] = 'N;';
  174. $param['store_name'] = $store_info['store_name'];
  175. $param['store_id'] = session('store_id');
  176. $param['type_id'] = '0';
  177. $param['goods_image'] = $pic_array['goods_image'][0];
  178. $param['goods_marketprice'] = $record['goods_store_price'];
  179. $param['goods_costprice'] = $record['goods_store_price'];
  180. $param['goods_discount'] = 1;
  181. $param['goods_price'] = $record['goods_store_price'];
  182. //$param['goods_show'] = '1';
  183. $param['goods_commend'] = $record['goods_commend'];
  184. $param['goods_addtime'] = TIMESTAMP;
  185. $param['goods_shelftime'] = TIMESTAMP; //上架时间
  186. $param['goods_attr'] = '';
  187. $param['goods_body'] = $record['goods_body'];
  188. $param['goods_state'] = '0';
  189. $param['goods_verify'] = '1';
  190. $param['areaid_1'] = intval(input('post.province_id'));
  191. $param['areaid_2'] = intval(input('post.city_id'));
  192. $param['goods_stcids'] = ',' . implode(',', array_unique(input('post.sgcate_id/a'))) . ',';
  193. $param['goods_serial'] = $record['goods_serial'];
  194. $goods_id = $model_store_goods->addGoodsCommon($param);
  195. //添加库存
  196. $param = array();
  197. $param['goods_commonid'] = $goods_id;
  198. $param['goods_name'] = $record['goods_name'];
  199. $param['gc_id'] = intval(input('post.gc_id'));
  200. $param['store_id'] = session('store_id');
  201. $param['goods_image'] = $pic_array['goods_image'][0];
  202. $param['goods_marketprice'] = $record['goods_store_price'];
  203. $param['goods_price'] = $record['goods_store_price'];
  204. //$param['goods_show'] = '1';
  205. $param['goods_commend'] = $record['goods_commend'];
  206. $param['goods_addtime'] = TIMESTAMP;
  207. $param['goods_edittime'] = TIMESTAMP;
  208. $param['goods_state'] = '0';
  209. $param['goods_verify'] = '1';
  210. $param['areaid_1'] = intval(input('post.province_id'));
  211. $param['areaid_2'] = intval(input('post.city_id'));
  212. $param['goods_stcids'] = ',' . implode(',', array_unique(input('post.sgcate_id/a'))) . ',';
  213. $param['goods_storage'] = $record['spec_goods_storage'];
  214. $param['goods_serial'] = $record['goods_serial'];
  215. $param['gc_id_1'] = intval(input('post.cls_1'));
  216. $param['gc_id_2'] = intval(input('post.cls_2'));
  217. $param['gc_id_3'] = intval(input('post.cls_3'));
  218. $param['goods_promotion_price'] = $param['goods_price'];
  219. $param['goods_spec'] = 'N;';
  220. $param['store_name'] = $store_info['store_name'];
  221. $goods_id1 = $model_store_goods->addGoods($param);
  222. //规格导入
  223. // 更新常用分类信息
  224. $goods_class = $model_goodsclass->getGoodsClassLineForTag(input('post.gc_id'));
  225. $goods_id_str .= "," . $goods_id;
  226. if ($goods_id) {
  227. /**
  228. * 添加商品的店铺分类表
  229. */
  230. /**
  231. * 商品多图的添加
  232. */
  233. if (!empty($pic_array['goods_image']) && is_array($pic_array['goods_image'])) {
  234. $insert_array = array();
  235. foreach ($pic_array['goods_image'] as $pic) {
  236. if ($pic == '')
  237. continue;
  238. $param = array();
  239. $param['goodsimage_url'] = $pic;
  240. $param['store_id'] = session('store_id');
  241. $param['goods_commonid'] = $goods_id;
  242. $insert_array[] = $param;
  243. }
  244. //$rs = model('upload');
  245. //$rs = $rs->add($param);
  246. $rs = $model_store_goods->addGoodsImagesAll($insert_array);
  247. }
  248. }
  249. }
  250. if ($goods_id_str != "") {
  251. View::assign('goods_id_str', substr($goods_id_str, 1, strlen($goods_id_str)));
  252. }
  253. }
  254. View::assign('step', '4');
  255. }
  256. /**
  257. * 相册分类
  258. */
  259. $model_album = model('album');
  260. $param = array();
  261. $param['store_id'] = session('store_id');
  262. $aclass_info = $model_album->getAlbumclassList($param);
  263. View::assign('aclass_info', $aclass_info);
  264. /* 设置卖家当前菜单 */
  265. $this->setSellerCurMenu('seller_taobao_import');
  266. $this->setSellerCurItem();
  267. return View::fetch($this->template_dir . 'index');
  268. }
  269. public function import_image()
  270. {
  271. View::assign('session_id', $this->app->session->getId());
  272. return View::fetch($this->template_dir . 'import_image');
  273. }
  274. public function upload()
  275. {
  276. $time = TIMESTAMP;
  277. if (isset($_FILES["Filedata"]) || !is_uploaded_file($_FILES["Filedata"]["tmp_name"]) || $_FILES["Filedata"]["error"] != 0) {
  278. $store_id = session('store_id');
  279. $path = BASE_UPLOAD_PATH . DIRECTORY_SEPARATOR . ATTACH_GOODS . DIRECTORY_SEPARATOR . $store_id . DIRECTORY_SEPARATOR . date('Ymd', $time); //取得上传图片的绝对路径
  280. $SID = $store_id . "_";
  281. if (!is_dir($path)) {
  282. mkdir($path, 0777, true);
  283. } //如果目录不存在,则创建
  284. $path = realpath($path) . '/';
  285. $filetype = '.jpg'; //后缀
  286. $upload_file = $_FILES['Filedata']; //上传的数据
  287. $file_info = pathinfo($upload_file['name']); //图片数组
  288. $sourimgname = $file_info['filename']; //不带后缀文件名,入库
  289. $save_name = date('YmdHis', $time) . rand(10000, 99999);
  290. $rukuimgname = $SID . $save_name . $filetype; //带后缀入库的名字
  291. $save = $path . $rukuimgname; //将要保存到服务器的路径
  292. $name = $_FILES['Filedata']['tmp_name']; //上传到服务器的临时文件
  293. //echo $save;
  294. if (!move_uploaded_file($name, $save)) {
  295. exit;
  296. }
  297. //生成不同规格大小的图片
  298. $fz60 = $path . $SID . $save_name . '_60.jpg';
  299. $fz240 = $path . $SID . $save_name . '_240.jpg';
  300. $fz360 = $path . $SID . $save_name . '_360.jpg';
  301. $fz1280 = $path . $SID . $save_name . '_1280.jpg';
  302. if (copy($save, $fz60)) {
  303. //更改图片大小
  304. $this->resizeimage($fz60, 60, 60, $fz60);
  305. }
  306. if (copy($save, $fz240)) {
  307. //更改图片大小
  308. $this->resizeimage($fz240, 240, 240, $fz240);
  309. }
  310. if (copy($save, $fz360)) {
  311. //更改图片大小
  312. $this->resizeimage($fz360, 360, 360, $fz360);
  313. }
  314. if (copy($save, $fz1280)) {
  315. //更改图片大小
  316. $this->resizeimage($fz1280, 1280, 1280, $fz1280);
  317. }
  318. Db::startTrans();
  319. try {
  320. //更新goods表
  321. $result = model('goods')->editGoods(array('goods_image' => $rukuimgname), array('goods_image' => $sourimgname));
  322. if (!$result) {
  323. // throw new \think\Exception('更新goods表失败', 10006);
  324. }
  325. //更新goodscommon表
  326. $temp = Db::name('goodscommon')->where(array(array('store_id', '=', $this->store_info['store_id']), array('goods_body', 'like', '%' . $sourimgname . '%')))->order('goods_commonid desc')->find();
  327. if ($temp) {
  328. $temp['goods_body'] = preg_replace('/"([^"]+)' . $sourimgname . '([^"]+)"/i', '"' . UPLOAD_SITE_URL . "/home/store/goods/" . session('store_id') . "/" . date('Ymd', $time) . "/" . $rukuimgname . '"', $temp['goods_body']);
  329. model('goods')->editGoodsCommon(array('goods_body' => $temp['goods_body']), array('goods_commonid' => $temp['goods_commonid']));
  330. }
  331. $result = model('goods')->editGoodsCommon(array('goods_image' => $rukuimgname), array('goods_image' => $sourimgname));
  332. if (!$result) {
  333. // throw new \think\Exception('更新goodscommon表失败', 10006);
  334. }
  335. //更新goodsimages表
  336. $result = model('goods')->editGoodsImages(array('goodsimage_url' => $rukuimgname), array('goodsimage_url' => $sourimgname));
  337. if (!$result) {
  338. // throw new \think\Exception('更新goodsimages表失败', 10006);
  339. }
  340. //插入albumpic表
  341. $insert_array = array();
  342. $insert_array['apic_name'] = $rukuimgname;
  343. $insert_array['apic_tag'] = '';
  344. $insert_array['aclass_id'] = 1;
  345. $insert_array['apic_cover'] = $rukuimgname;
  346. $insert_array['apic_size'] = '';
  347. $insert_array['apic_spec'] = '';
  348. $insert_array['apic_uploadtime'] = $time;
  349. $insert_array['store_id'] = $store_id;
  350. $result = model('album')->addAlbumpic($insert_array);
  351. if (!$result) {
  352. // throw new \think\Exception('插入albumpic表失败', 10006);
  353. }
  354. } catch (\Exception $e) {
  355. Db::rollback();
  356. throw new \think\Exception($e->getMessage(), 10006);
  357. }
  358. Db::commit();
  359. }
  360. }
  361. /*
  362. * 图片缩略图
  363. */
  364. private function resizeimage($srcfile, $ratew = '', $rateh = '', $filename = "")
  365. {
  366. $size = getimagesize($srcfile);
  367. switch ($size[2]) {
  368. case 1:
  369. $img = imagecreatefromgif($srcfile);
  370. break;
  371. case 2:
  372. $img = imagecreatefromjpeg($srcfile); //从源文件建立一个新图片
  373. break;
  374. case 3:
  375. $img = imagecreatefrompng($srcfile);
  376. break;
  377. default:
  378. exit;
  379. }
  380. //源图片的宽度和高度
  381. $srcw = imagesx($img);
  382. echo '源文件的宽度' . $srcw . '<br />';
  383. $srch = imagesy($img);
  384. echo '源文件的高度' . $srch . '<br />';
  385. //目的图片的宽度和高度
  386. $dstw = $ratew;
  387. $dsth = $rateh;
  388. //新建一个真彩色图像
  389. echo '新图片的宽度' . $dstw . '高度' . $dsth . '<br />';
  390. $im = imagecreatetruecolor($dstw, $dsth);
  391. $black = imagecolorallocate($im, 255, 255, 255);
  392. imagefilledrectangle($im, 0, 0, $dstw, $dsth, $black);
  393. imagecopyresized($im, $img, 0, 0, 0, 0, $dstw, $dsth, $srcw, $srch);
  394. // 以 JPEG 格式将图像输出到浏览器或文件
  395. if ($filename) {
  396. //图片保存输出
  397. imagejpeg($im, $filename, 100);
  398. }
  399. //释放图片
  400. imagedestroy($im);
  401. imagedestroy($img);
  402. }
  403. /**
  404. * 得到数组变量的GBK编码
  405. *
  406. * @param array $key 数组
  407. * @return array 数组类型的返回结果
  408. */
  409. private function getGBK($key)
  410. {
  411. /**
  412. * 转码
  413. */
  414. if (strtoupper(CHARSET) == 'GBK' && !empty($key)) {
  415. if (is_array($key)) {
  416. $result = var_export($key, true); //变为字符串
  417. $result = iconv('UTF-8', 'GBK', $result);
  418. eval("\$result = $result;"); //转换回数组
  419. } else {
  420. $result = iconv('UTF-8', 'GBK', $key);
  421. }
  422. }
  423. return $result;
  424. }
  425. /**
  426. * unicode转为utf8
  427. * @param string $str 待转的字符串
  428. * @return string
  429. */
  430. function unicodeToUtf8($str, $order = "little")
  431. {
  432. $utf8string = "";
  433. $n = strlen($str);
  434. for ($i = 0; $i < $n; $i++) {
  435. if ($order == "little") {
  436. $val = str_pad(dechex(ord($str[$i + 1])), 2, 0, STR_PAD_LEFT) .
  437. str_pad(dechex(ord($str[$i])), 2, 0, STR_PAD_LEFT);
  438. } else {
  439. $val = str_pad(dechex(ord($str[$i])), 2, 0, STR_PAD_LEFT) .
  440. str_pad(dechex(ord($str[$i + 1])), 2, 0, STR_PAD_LEFT);
  441. }
  442. $val = intval($val, 16); // 由于上次的.连接,导致$val变为字符串,这里得转回来。
  443. $i++; // 两个字节表示一个unicode字符。
  444. $c = "";
  445. if ($val < 0x7F) { // 0000-007F
  446. $c .= chr($val);
  447. } elseif ($val < 0x800) { // 0080-07F0
  448. $c .= chr(0xC0 | ($val / 64));
  449. $c .= chr(0x80 | ($val % 64));
  450. } else { // 0800-FFFF
  451. $c .= chr(0xE0 | (($val / 64) / 64));
  452. $c .= chr(0x80 | (($val / 64) % 64));
  453. $c .= chr(0x80 | ($val % 64));
  454. }
  455. $utf8string .= $c;
  456. }
  457. /* 去除bom标记 才能使内置的iconv函数正确转换 */
  458. if (ord(substr($utf8string, 0, 1)) == 0xEF && ord(substr($utf8string, 1, 2)) == 0xBB && ord(substr($utf8string, 2, 1)) == 0xBF) {
  459. $utf8string = substr($utf8string, 3);
  460. }
  461. return $utf8string;
  462. }
  463. private function get_goods_image($pic_string)
  464. {
  465. if ($pic_string == '') {
  466. return false;
  467. }
  468. $pic_array = explode(';', $pic_string);
  469. if (!empty($pic_array) && is_array($pic_array)) {
  470. $array = array();
  471. $goods_image = array();
  472. $multi_image = array();
  473. $i = 0;
  474. foreach ($pic_array as $v) {
  475. if ($v != '') {
  476. $line = explode(':', $v); //[0] 文件名tbi [2] 排序
  477. $goods_image[] = $line[0];
  478. }
  479. }
  480. $array['goods_image'] = array_unique($goods_image);
  481. $str = implode(',', $array['goods_image']) . "\r\n";
  482. file_put_contents('imgarr.txt', $str, FILE_APPEND);
  483. return $array;
  484. } else {
  485. return false;
  486. }
  487. }
  488. /**
  489. * 淘宝数据字段名
  490. *
  491. * @return array
  492. */
  493. private function taobao_fields()
  494. {
  495. return array(
  496. 'goods_name' => '宝贝名称',
  497. 'cid' => '宝贝类目',
  498. 'goods_form' => '新旧程度',
  499. 'goods_store_price' => '宝贝价格',
  500. 'spec_goods_storage' => '宝贝数量',
  501. 'goods_indate' => '有效期',
  502. 'goods_transfee_charge' => '运费承担',
  503. 'py_price' => '平邮',
  504. 'es_price' => 'EMS',
  505. 'kd_price' => '快递',
  506. //'goods_show' => '放入仓库',
  507. 'spec' => '销售属性别名',
  508. 'goods_commend' => '橱窗推荐',
  509. 'goods_body' => '宝贝描述',
  510. 'goods_image' => '新图片',
  511. 'goods_serial' => '商家编码'
  512. );
  513. }
  514. /**
  515. * 每个字段所在CSV中的列序号,从0开始算
  516. *
  517. * @param array $title_arr
  518. * @param array $import_fields
  519. * @return array
  520. */
  521. private function taobao_fields_cols($title_arr, $import_fields)
  522. {
  523. $fields_cols = array();
  524. foreach ($import_fields as $k => $field) {
  525. $pos = array_search($field, $title_arr);
  526. if ($pos !== false) {
  527. $fields_cols[$k] = $pos;
  528. }
  529. }
  530. return $fields_cols;
  531. }
  532. /**
  533. * 解析淘宝助理CSV数据
  534. *
  535. * @param string $csv_string
  536. * @return string
  537. */
  538. private function parse_taobao_csv($csv_string)
  539. {
  540. //防止乱码
  541. $scount = strpos($csv_string, "宝贝名称");
  542. $csv_string = substr($csv_string, $scount);
  543. /* 定义CSV文件中几个标识性的字符的ascii码值 */
  544. define('ORD_SPACE', 32); // 空格
  545. define('ORD_QUOTE', 34); // 双引号
  546. define('ORD_TAB', 9); // 制表符
  547. define('ORD_N', 10); // 换行\n
  548. define('ORD_R', 13); // 换行\r
  549. /* 字段信息 */
  550. $import_fields = $this->taobao_fields(); // 需要导入的字段在CSV中显示的名称
  551. $fields_cols = array(); // 每个字段所在CSV中的列序号,从0开始算
  552. $csv_col_num = 0; // csv文件总列数
  553. $pos = 0; // 当前的字符偏移量
  554. $status = 0; // 0标题未开始 1标题已开始
  555. $title_pos = 0; // 标题开始位置
  556. $records = array(); // 记录集
  557. $field = 0; // 字段号
  558. $start_pos = 0; // 字段开始位置
  559. $field_status = 0; // 0未开始 1双引号字段开始 2无双引号字段开始
  560. $line = 0; // 数据行号
  561. while ($pos < strlen($csv_string)) {
  562. $t = ord($csv_string[$pos]); // 每个UTF-8字符第一个字节单元的ascii码
  563. $next = ord($csv_string[$pos + 1]);
  564. $next2 = ord($csv_string[$pos + 2]);
  565. $next3 = ord($csv_string[$pos + 3]);
  566. if ($status == 0 && !in_array($t, array(ORD_SPACE, ORD_TAB, ORD_N, ORD_R))) {
  567. $status = 1;
  568. $title_pos = $pos;
  569. }
  570. if ($status == 1) {
  571. if ($field_status == 0 && $t == ORD_N) {
  572. static $flag = null;
  573. if ($flag === null) {
  574. $title_str = substr($csv_string, $title_pos, $pos - $title_pos);
  575. $title_arr = explode("\t", trim($title_str));
  576. $fields_cols = $this->taobao_fields_cols($title_arr, $import_fields);
  577. if (count($fields_cols) != count($import_fields)) {
  578. return false;
  579. }
  580. $csv_col_num = count($title_arr); // csv总列数
  581. $flag = 1;
  582. }
  583. if ($next == ORD_QUOTE) {
  584. $field_status = 1; // 引号数据单元开始
  585. $start_pos = $pos = $pos + 2; // 数据单元开始位置(相对\n偏移+2)
  586. } else {
  587. $field_status = 2; // 无引号数据单元开始
  588. $start_pos = $pos = $pos + 1; // 数据单元开始位置(相对\n偏移+1)
  589. }
  590. continue;
  591. }
  592. if ($field_status == 1 && $t == ORD_QUOTE && in_array($next, array(ORD_N, ORD_R, ORD_TAB))) { // 引号+换行 或 引号+\t
  593. $records[$line][$field] = addslashes(substr($csv_string, $start_pos, $pos - $start_pos));
  594. $field++;
  595. if ($field == $csv_col_num) {
  596. $line++;
  597. $field = 0;
  598. $field_status = 0;
  599. continue;
  600. }
  601. if (($next == ORD_N && $next2 == ORD_QUOTE) || ($next == ORD_TAB && $next2 == ORD_QUOTE) || ($next == ORD_R && $next2 == ORD_QUOTE)) {
  602. $field_status = 1;
  603. $start_pos = $pos = $pos + 3;
  604. continue;
  605. }
  606. if (($next == ORD_N && $next2 != ORD_QUOTE) || ($next == ORD_TAB && $next2 != ORD_QUOTE) || ($next == ORD_R && $next2 != ORD_QUOTE)) {
  607. $field_status = 2;
  608. $start_pos = $pos = $pos + 2;
  609. continue;
  610. }
  611. if ($next == ORD_R && $next2 == ORD_N && $next3 == ORD_QUOTE) {
  612. $field_status = 1;
  613. $start_pos = $pos = $pos + 4;
  614. continue;
  615. }
  616. if ($next == ORD_R && $next2 == ORD_N && $next3 != ORD_QUOTE) {
  617. $field_status = 2;
  618. $start_pos = $pos = $pos + 3;
  619. continue;
  620. }
  621. }
  622. if ($field_status == 2 && in_array($t, array(ORD_N, ORD_R, ORD_TAB))) { // 换行 或 \t
  623. $records[$line][$field] = addslashes(substr($csv_string, $start_pos, $pos - $start_pos));
  624. $field++;
  625. if ($field == $csv_col_num) {
  626. $line++;
  627. $field = 0;
  628. $field_status = 0;
  629. continue;
  630. }
  631. if (($t == ORD_N && $next == ORD_QUOTE) || ($t == ORD_TAB && $next == ORD_QUOTE) || ($t == ORD_R && $next == ORD_QUOTE)) {
  632. $field_status = 1;
  633. $start_pos = $pos = $pos + 2;
  634. continue;
  635. }
  636. if (($t == ORD_N && $next != ORD_QUOTE) || ($t == ORD_TAB && $next != ORD_QUOTE) || ($t == ORD_R && $next != ORD_QUOTE)) {
  637. $field_status = 2;
  638. $start_pos = $pos = $pos + 1;
  639. continue;
  640. }
  641. if ($t == ORD_R && $next == ORD_N && $next2 == ORD_QUOTE) {
  642. $field_status = 1;
  643. $start_pos = $pos = $pos + 3;
  644. continue;
  645. }
  646. if ($t == ORD_R && $next == ORD_N && $next2 != ORD_QUOTE) {
  647. $field_status = 2;
  648. $start_pos = $pos = $pos + 2;
  649. continue;
  650. }
  651. }
  652. }
  653. if ($t > 0 && $t <= 127) {
  654. $pos++;
  655. } elseif (192 <= $t && $t <= 223) {
  656. $pos += 2;
  657. } elseif (224 <= $t && $t <= 239) {
  658. $pos += 3;
  659. } elseif (240 <= $t && $t <= 247) {
  660. $pos += 4;
  661. } elseif (248 <= $t && $t <= 251) {
  662. $pos += 5;
  663. } elseif ($t == 252 || $t == 253) {
  664. $pos += 6;
  665. } else {
  666. $pos++;
  667. }
  668. }
  669. $return = array();
  670. foreach ($records as $key => $record) {
  671. foreach ($record as $k => $col) {
  672. $col = trim($col); // 去掉数据两端的空格
  673. /* 对字段数据进行分别处理 */
  674. switch ($k) {
  675. case $fields_cols['goods_body']:
  676. $return[$key]['goods_body'] = str_replace('\"\"', '"', $col);
  677. break;
  678. case $fields_cols['goods_image']:
  679. $return[$key]['goods_image'] = trim($col, '"');
  680. break;
  681. //case $fields_cols['goods_show'] : $return[$key]['goods_show'] = $col == 1 ? 0 : 1; break;
  682. case $fields_cols['goods_name']:
  683. $return[$key]['goods_name'] = $col;
  684. break;
  685. case $fields_cols['spec_goods_storage']:
  686. $return[$key]['spec_goods_storage'] = $col;
  687. break;
  688. case $fields_cols['goods_store_price']:
  689. $return[$key]['goods_store_price'] = $col;
  690. break;
  691. case $fields_cols['goods_commend']:
  692. $return[$key]['goods_commend'] = $col;
  693. break;
  694. case $fields_cols['spec']:
  695. $return[$key]['spec'] = $col;
  696. break;
  697. case $fields_cols['sale_attr']:
  698. $return[$key]['sale_attr'] = $col;
  699. break;
  700. case $fields_cols['goods_form']:
  701. $return[$key]['goods_form'] = $col;
  702. break;
  703. case $fields_cols['goods_transfee_charge']:
  704. $return[$key]['goods_transfee_charge'] = $col;
  705. break;
  706. case $fields_cols['py_price']:
  707. $return[$key]['py_price'] = $col;
  708. break;
  709. case $fields_cols['es_price']:
  710. $return[$key]['es_price'] = $col;
  711. break;
  712. case $fields_cols['kd_price']:
  713. $return[$key]['kd_price'] = $col;
  714. break;
  715. case $fields_cols['goods_serial']:
  716. $return[$key]['goods_serial'] = $col;
  717. break;
  718. // case $fields_cols['goods_indate'] : $return[$key]['goods_indate'] = $col; break;
  719. }
  720. }
  721. }
  722. return $return;
  723. }
  724. }