首页 » PHP » 正文

php读取、导入淘宝数据包

以下场景均为utf-8编码,包括php页面和数据库编码均为utf-8。

1、关键函数,解决读取淘宝csv数据包中文乱码的问题

  function fopen_utf8($filename){
    $encoding='';
    $handle = fopen($filename, 'r');
    $bom = fread($handle, 2);
    rewind($handle);
    if($bom === chr(0xff).chr(0xfe)  || $bom === chr(0xfe).chr(0xff)){
            // UTF16 Byte Order Mark present
         $encoding = 'UTF-16';
    } else {
        $file_sample = fread($handle, 1000) + 'e'; //read first 1000 bytes
        // + e is a workaround for mb_string bug
        rewind($handle);
        $encoding = mb_detect_encoding($file_sample , 'UTF-8, UTF-7, ASCII, EUC-JP,SJIS, eucJP-win, SJIS-win, JIS, ISO-2022-JP');
    }
    if ($encoding){
        stream_filter_append($handle, 'convert.iconv.'.$encoding.'/UTF-8');
    }
    return  ($handle);
}

2、上传文件,这里我用现成的上传类

$upfile=spClass("uploadFile");
$upfile->allow_types="csv";
$filename=$upfile->upload_file($_FILES['file']);

3、读入上传的淘宝数据包csv文件做导入数据库的操作

$handle = $this->fopen_utf8($filename);
$list=array();
while (($cols = fgetcsv($handle,0,'	'))) {
	$list[]=$cols;       
}
fclose($handle);
unset($list[0]);
unset($list[1]);
unset($list[2]);

foreach ($list as $key=>$v) {//开始遍历导入
...
}

=================================================
根据淘宝商品id抓取商品信息:

$arrContextOptions=array(
	"ssl"=>array(
		"verify_peer"=>false,
		"verify_peer_name"=>false,
	),
);	
$url='https://detail.tmall.com/item.htm?id='.$id;	
$response = file_get_contents($url, false, stream_context_create($arrContextOptions));
echo $response;
博主的文章或程序如果给您带来了价值,感谢您打赏一二
微信扫码支付 支付宝扫码支付

发表评论