<?php
/**
* Imports data from a binary file in chunks to manage memory usage.
*
* @param string $filePath Path to the binary file.
* @param callable $callback A callback function to process each chunk of data.
* The callback function receives the chunk as a string.
* @param int $chunkSize The size of each chunk in bytes. Default is 4096.
* @return bool True on success, false on failure.
*/
function importBinaryFileInChunks(string $filePath, callable $callback, int $chunkSize = 4096): bool
{
if (!file_exists($filePath)) {
error_log("File not found: " . $filePath);
return false;
}
$fileHandle = fopen($filePath, 'rb'); // Open the file in binary read mode.
if ($fileHandle === false) {
error_log("Failed to open file: " . $filePath);
return false;
}
$buffer = '';
while (!feof($fileHandle)) {
$chunk = fread($fileHandle, $chunkSize); // Read a chunk of data.
if ($chunk === false) {
$error = error_get_last();
error_log("Error reading file: " . $error['message']);
fclose($fileHandle);
return false;
}
$buffer .= $chunk; // Append the chunk to the buffer.
// Process the chunk using the callback function.
$callback($buffer);
$buffer = ''; // Clear the buffer.
}
fclose($fileHandle); // Close the file handle.
return true;
}
//Example usage:
/*
function processChunk(string $chunk): void{
//Do something with the chunk of data
echo "Processing chunk of size: " . strlen($chunk) . "\n";
}
if (importBinaryFileInChunks('large_binary_file.bin', 'processChunk', 1024)) {
echo "File imported successfully.\n";
} else {
echo "File import failed.\n";
}
*/
?>
Add your comment