SellerTaobaoImport.php 33 KB

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