What are some alternative methods to using a hidden iframe for exporting data from a PHP website?

Using a hidden iframe for exporting data from a PHP website can be cumbersome and not the most efficient method. An alternative approach is to use AJAX to send a request to the server, process the data, and then return it to the client for download. This method allows for a more seamless user experience and eliminates the need for a hidden iframe.

<?php
if(isset($_POST['export_data'])) {
    // Process data and generate export file
    $data = "This is the data to export";
    
    // Set headers for file download
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="exported_data.txt"');
    
    // Output data to client
    echo $data;
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Export Data</title>
</head>
<body>
    <button id="exportButton">Export Data</button>
    
    <script>
        document.getElementById('exportButton').addEventListener('click', function() {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'export.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.responseType = 'blob';
            
            xhr.onload = function() {
                if(xhr.status === 200) {
                    var blob = new Blob([xhr.response], {type: 'application/octet-stream'});
                    var url = window.URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = 'exported_data.txt';
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            
            xhr.send('export_data=true');
        });
    </script>
</body>
</html>