如何将PHP页面中的Div标签内容逐行导出至CSV文件
<br>) to CSV in PHP Got it, let's walk through how to export the content from your 65+ .demo-content divs into a CSV file, where each <br> tag translates to a new row in the CSV. Here's a straightforward approach tailored to your code structure:
Step 1: Collect Content Instead of Echoing Directly
First, instead of sending content straight to the browser, we'll store all desired lines in an array. This makes processing and writing to CSV much easier. Modify your existing code to build this array:
<?php // Initialize empty array to hold all CSV rows $csvRows = []; // Process the first static content div $staticLines = [ "!-------------------------------------------------------------------------------", "! Menu Configuration", "!-------------------------------------------------------------------------------", "menu.panel = panelRight", "menu.autoLoad = logo", "!-------------------------------------------------------------------------------", "! Fast Menus", "!-------------------------------------------------------------------------------" ]; $csvRows = array_merge($csvRows, $staticLines); // Reset database statement pointer (in case you've fetched rows already) mysqli_data_seek($statement, 0); // Process dynamic database rows while ($row = mysqli_fetch_assoc($statement)) { if (in_array($row['id'], [1, 2])) { // Adjust this to include all your target IDs $btnLines = [ "btn{$row['btn']}width = {$row['btnwidth']}", "btn{$row['btn']}height = {$row['btnheight']}", "btn{$row['btn']}x = {$row['btnx']}", "btn{$row['btn']}y = {$row['btny']}", htmlspecialchars("btn{$row['btn']}text = {$row['btntext']}{$row['btntext1']}{$row['btntext2']}"), "btn{$row['btn']}icon = {$row['btnicon']}", "btn{$row['btn']}menu = {$row['btnmenu']}", "btn{$row['btn']}plu = {$row['btnplu']}", "btn{$row['btn']}command = {$row['btncommand']}", "btn{$row['btn']}exitType = {$row['btnexitType']}", "btn{$row['btn']}exitValue = {$row['btnexitValue']}" ]; $csvRows = array_merge($csvRows, $btnLines); } } ?>
Step 2: Export the Array to CSV
Once all lines are collected, add this code to trigger a CSV download in the user's browser:
<?php // Set headers to force CSV download header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="menu_config.csv"'); // Open output stream $output = fopen('php://output', 'w'); // Write each line as a single CSV row foreach ($csvRows as $line) { // fputcsv automatically escapes commas, quotes, and special characters fputcsv($output, [$line]); } // Clean up and exit fclose($output); exit; ?>
Key Notes:
- Avoid
<br>in Data: We replaced<br>with array items directly to avoid extra parsing. If you need to keep<br>for page display, you can duplicate the logic (echo for display, add to array for CSV). - Special Character Handling:
fputcsvtakes care of escaping commas, quotes, and newlines in your content, so your CSV will be properly formatted without breaking rows. - Database Pointer Reset:
mysqli_data_seek($statement, 0)ensures you fetch all rows from the start, even if you've already used the statement elsewhere.
Alternative: Capture Rendered HTML (If You Can't Modify Existing Echo Code)
If you don't want to rewrite your existing echo logic, use output buffering to capture the page content, then extract and process the divs:
<?php ob_start(); // Start capturing page output // Paste your existing HTML/PHP code here (all the divs with echo statements) $pageContent = ob_get_clean(); // Get the captured content // Parse HTML to extract .demo-content divs $dom = new DOMDocument(); libxml_use_internal_errors(true); // Suppress HTML formatting warnings $dom->loadHTML($pageContent); libxml_clear_errors(); $xpath = new DOMXPath($dom); $divs = $xpath->query('//div[@class="demo-content"]'); $csvRows = []; foreach ($divs as $div) { // Replace all <br> variants with newlines $content = str_replace(['<br>', '<br/>', '<br />'], "\n", $div->nodeValue); // Split into lines, trim whitespace, and remove empty lines $lines = array_filter(array_map('trim', explode("\n", $content))); $csvRows = array_merge($csvRows, $lines); } // Export to CSV using the same header/fputcsv code from Step 2 ?>
This approach lets you keep your existing page output while still capturing the data for CSV export.
内容的提问来源于stack exchange,提问作者Francois van Ellinckhuyzen

