一:大数组转存到文件里,可以考虑逐行写入,并配合多进程来写入
/*
* 参 数:$file 字符串 文件名
* $key 字符串 数组键名
* $value 字符串 数组键值
* $step 字符串 当前程序步骤,只有三个值:初始化init/执行中doing/完成done
* 功 能:一维数组大数据量写入php文件时,为了避免过多的占用内存,使用追加的方式写入
* 作 者:yishuguang
*/
function appendArrayToFile($file, $key = '', $value = '', $step = 'init') {
static $rows = array();
$md5String = md5($file);
//文件初始化
if($step == 'init') {
file_put_contents($file, '<?php return array('."\n", LOCK_EX);
return true;
}
//文件追加
if($step == 'doing') {
if(!isset($rows[$md5String])) $rows[$md5String] = array();
if($key != '' || $value != '') {
$rows[$md5String][] = "\t'".addslashes($key)."'=>'".addslashes($value)."',\n";
}
}
//符合一定的条件,数据写入文件
if(count($rows[$md5String]) > ARRAY_TO_PHP_APPEND_ROW_LIMIT || $step == 'done') {
file_put_contents($file, implode('', $rows[$md5String]), FILE_APPEND);
unset($rows[$md5String]);
}
if($step == 'done') {
file_put_contents($file, ");", FILE_APPEND);
}
return true;
}
使用方法:
$fileUnionLo = FILE_DIR.'/unionLo.php';
appendArrayToFile($fileUnionLo, '', '', 'init');
foreach($tempUsers as $uid => $url) { //$tempUsers是个很大的数组
if(is_array($url)) {
foreach($url as $innerUrl) {
appendArrayToFile($fileUnionLo, $innerUrl, $uid, 'doing');
}
} else {
appendArrayToFile($fileUnionLo, $url, $uid, 'doing');
}
}
appendArrayToFile($fileUnionLo, '', '', 'done');
二:抓取数据的时候利用curl开启多个进程抓取
//批量处理所有的分页请求
$handles = array();
$multiHandle = curl_multi_init();
for($i = 1; $i < $totalPage; $i++) {
$url = URL_JIFEN_USER.$i;
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_HEADER, 0);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_multi_add_handle($multiHandle, $handle);
$handles[$i] = $handle;
}
$runing = 0;
do {
$flag = curl_multi_exec($multiHandle, $runing);
} while($flag === CURLM_CALL_MULTI_PERFORM || $runing > 0);
//获取数据
$jsons = array();
$errorUrls = array();
foreach($handles as $page => $handle) {
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
//返回状态码为200表示请求正常完成
if($httpCode == 200) {
$jsons[$page] = curl_multi_getcontent($handle);
} else {
$errorUrls[] = str_replace('HTTP://', 'http://', curl_getinfo($handle, CURLINFO_EFFECTIVE_URL));
}
curl_multi_remove_handle($multiHandle, $handle);
}
curl_multi_close($multiHandle);