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