file_get_contents() 是在 PHP 中读取文件的最优化方式,但是 - 因为您是在内存中读取文件您总是受限于可用的内存量。
如果您拥有正确的权限,您可以发出ini_set('memory_limit', -1),但您仍然会受到系统上可用内存量的限制,这对所有编程语言都很常见。
唯一的解决方案是分块读取文件,您可以使用file_get_contents() 和第四个和第五个参数($offset 和$maxlen - 以字节指定):
string file_get_contents(string $filename[, bool $use_include_path = false[, resource $context[, int $offset = -1[, int $maxlen = -1]]]])
这是我使用此技术提供大型下载文件的示例:
public function Download($path, $speed = null)
{
if (is_file($path) === true)
{
set_time_limit(0);
while (ob_get_level() > 0)
{
ob_end_clean();
}
$size = sprintf('%u', filesize($path));
$speed = (is_int($speed) === true) ? $size : intval($speed) * 1024;
header('Expires: 0');
header('Pragma: public');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . $size);
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Content-Transfer-Encoding: binary');
for ($i = 0; $i <= $size; $i = $i + $speed)
{
ph()->HTTP->Flush(file_get_contents($path, false, null, $i, $speed));
ph()->HTTP->Sleep(1);
}
exit();
}
return false;
}
另一种选择是使用优化程度较低的 fopen()、feof()、fgets() 和 fclose() 函数,特别是如果您想一次获得整行,这里是 @987654321 @:
function SplitSQL($file, $delimiter = ';')
{
set_time_limit(0);
if (is_file($file) === true)
{
$file = fopen($file, 'r');
if (is_resource($file) === true)
{
$query = array();
while (feof($file) === false)
{
$query[] = fgets($file);
if (preg_match('~' . preg_quote($delimiter, '~') . '\s*$~iS', end($query)) === 1)
{
$query = trim(implode('', $query));
if (mysql_query($query) === false)
{
echo '<h3>ERROR: ' . $query . '</h3>' . "\n";
}
else
{
echo '<h3>SUCCESS: ' . $query . '</h3>' . "\n";
}
while (ob_get_level() > 0)
{
ob_end_flush();
}
flush();
}
if (is_string($query) === true)
{
$query = array();
}
}
return fclose($file);
}
}
return false;
}
您使用哪种技术实际上取决于您要执行的操作(正如您在 SQL 导入功能和下载功能中看到的那样),但 您总是必须以块的形式读取数据。