How can PHP be optimized to minimize resource usage when processing database records for file output?

To minimize resource usage when processing database records for file output in PHP, it is important to fetch records from the database in batches rather than all at once. This can be achieved by using LIMIT and OFFSET in SQL queries to retrieve a limited number of records at a time. Additionally, using efficient data processing techniques and optimizing memory usage can help improve performance and reduce resource consumption.

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Set batch size
$batchSize = 100;

// Retrieve records from the database in batches
$offset = 0;
do {
    $stmt = $pdo->prepare("SELECT * FROM mytable LIMIT $batchSize OFFSET $offset");
    $stmt->execute();
    
    // Process records
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // Output record to file
        // Example: fwrite($fileHandle, json_encode($row));
    }

    $offset += $batchSize;
} while ($stmt->rowCount() > 0);