php处理大的文件如何处理,php处理大文件 切割与合并

开发中有时候需要php对接外部接口,明显很多的因为大小而不能一次性上传,那么就需要涉及到对文件的切割:

下面来看下如何对文件进行切割:

php版本:

分割:$i    = 0;                               //分割的块编号

$fp   = fopen("hadoop.sql","rb");      //要分割的文件

$file = fopen("split_hash.txt","a");     //记录分割的信息的文本文件,实际生产环境存在redis更合适

while(!feof($fp)){

$handle = fopen("hadoop.{$i}.sql","wb");

fwrite($handle,fread($fp,5242880));//切割的块大小 5m

fwrite($file,"hadoop.{$i}.sql\r\n");

fclose($handle);

unset($handle);

$i++;

}

fclose ($fp);

fclose ($file);

echo "ok";

合并代码$hash = file_get_contents("split_hash.txt"); //读取分割文件的信息

$list = explode("\r\n",$hash);

$fp = fopen("hadoop2.sql","ab");     //合并后的文件名

foreach($list as $value){

if(!empty($value)) {

$handle = fopen($value,"rb");

fwrite($fp,fread($handle,filesize($value)));

fclose($handle);

unset($handle);

}

}

fclose($fp);

echo "ok";

这里提供一个类库:<?php

class File_split {

public $file;

public $cut_size = 1024;  //单位字节     2*1024*1024  2M

public function setCutSize($size) {

$this->cut_size = $size;

}

/**

* 获取当前切割文件的大小

* @return int

*/

public function getCutSize() {

return $this->cut_size;

}

public function cut($file) {

$this->file = $file;

if (!file_exists($this->file)) {

throw new Exception($file . "文件不存在");

}

$cut_m = 2;

$i = 0;

$fp = fopen($this->file, "rb");

$tempname = basename($this->file) . '_temp';

while (!feof($fp)) {

$handle = fopen("{$tempname}_{$i}.temp", "wb");

fwrite($handle, fread($fp, $this->cut_size));

fclose($handle);

unset($handle);

$i++;

}

fclose($fp);

return ['file' => basename($this->file), 'temp' => $tempname];

}

public function merge($info) {

if (count($info) != 2) {

throw new Exception("传递参数不正确", 1);

}

$fp = fopen($info['file'], "ab");

foreach (glob(__DIR__ . '/' . $info['temp'] . '_*.temp') as $file) {

$handle = fopen($file, "rb");

fwrite($fp, fread($handle, filesize($file)));

fclose($handle);

unset($handle);

@unlink($file);

}

fclose($fp);

return TRUE;

}

}

//$cm = new File_split();

//$info=$cm->cut('upload.html');

$data = [

'file' => 'uploadtest.html',

'temp' => 'upload.html_temp'

];

$cm = new File_split();

$flag = $cm->merge($data);

var_dump($flag);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值