PHPWord从数据库读取多个DOCX生成新文档问题求助
Hey there! As someone who’s tinkered with PHPWord a lot, let’s work through fixing your issue with merging multiple DOCX files from your database and adding text later. Since you’re new to PHP and PHPWord, I’ll keep this straightforward and actionable.
Core Problem Breakdown
Right now, your code is only pulling in one file because you’re probably either reinitializing your PhpWord instance inside the loop (overwriting previous content) or not properly copying elements from each source DOCX into your target document. Let’s fix that step by step.
Fixed Code with Explanations
Here’s how to adjust your code to merge multiple files and support later text appends:
// Initialize ONE target PhpWord instance (don't recreate this in the loop!) $phpWord = new \PhpOffice\PhpWord\PhpWord(); $phpWord->getSettings()->setThemeFontLang($languageEnGb); try { include ('DbConnection.php'); $GenratedFileID = "1"; $GenFileName = ''; // Use parameter-bound SQL to avoid injection and ensure reliability $sql = "SELECT S.FileID as fileID, G.GenratedFileName as GenFileName, S.FileContent as fileContent FROM your_source_table S JOIN your_generated_table G ON S.related_id = G.related_id WHERE G.GenratedFileID = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("s", $GenratedFileID); $stmt->execute(); $result = $stmt->get_result(); // Create a single section in your target document to hold all merged content $targetSection = $phpWord->addSection(); while ($row = $result->fetch_assoc()) { $fileBinary = $row['fileContent']; // Assuming your DB stores DOCX as binary BLOB $docName = $row['GenFileName']; // Load the source DOCX from the database's binary content $sourceDoc = \PhpOffice\PhpWord\IOFactory::load($fileBinary); // Copy EVERY element from the source document to the target section foreach ($sourceDoc->getSections() as $sourceSection) { foreach ($sourceSection->getElements() as $element) { // Clone the element to avoid overwriting references $targetSection->addElement(clone $element); } // Optional: Add a page break between merged files for clarity $targetSection->addPageBreak(); } } // Now append your additional text to the same target section $appendTextStyle = ['bold' => true, 'size' => 12]; $targetSection->addText('--- Post-Merge Added Text ---', $appendTextStyle); // Save the final merged document $writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007'); $outputFileName = 'final_merged_doc.docx'; $writer->save($outputFileName); echo "Success! Merged document saved as: " . $outputFileName; } catch (Exception $e) { echo "Oops, something went wrong: " . $e->getMessage(); }
Critical Fixes & Tips
- Reuse the target
PhpWordinstance: Creating a newPhpWord()inside the loop would erase all previous content—we only initialize it once at the top. - Clone elements: When copying elements from source to target, use
cloneto avoid reference issues that might break your content. - Parameterized SQL: This is safer than string interpolation and prevents bugs with special characters in your IDs.
- Check your DB storage: Make sure your
FileContentcolumn is aBLOBtype and that the DOCX data is saved without corruption (test by exporting one blob to a file and opening it manually). - Debug in NetBeans: Enable full error reporting (Project Properties > Run > Set
error_reporting = E_ALLin php.ini) to catch hidden warnings that might be stopping your loop.
内容的提问来源于stack exchange,提问作者Somaya Momtaz
相关产品推荐
相关产品推荐

