问题
I'm new with php Programming, I would like to ask if it is possible to save the generated files directly to database if you are using PHP word?
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter ->save("php://output");
Do I need to change the this lines? And I am using php5, mysqli
回答1:
No it isn't possible to save the PHPWord object directly to a database; you can save it to any of PHP's streams, whether that is a file on the server, or to the output stream (browser), but you'd have to write your own code to store it in any database, probably starting by sending the save() output to a file on the server first.
回答2:
Assume you have mysql table upload_file
with BLOB row where you will store your word file.
For example we have create-word.php:
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter ->save($somePathToUpload.$filename);
get contents from generated file by PhpWord:
$file = file_get_contents($somePathToUpload.$filename);
and use this variable in insert query like:
$query= "insert into upload_file(file_blob) values($file)";
and then delete generated file from disk:
unlink($somePathToUpload.$filename);
FORM SUBMITTING:
You can call this create-word.php file by form submitting, assume we have some form:
<form action='create-word.php'>
<input type='submit' value='submit'/>
</form>
JQUERY AJAX:
or you can call create-word.php by ajax like that:
$.ajax({
url: 'create-word.php',
type: 'post',
success: function(response){ // do stuff },
error: function(error){ console.log(error.responseText); }
});
UPDATE:
blob insertion more detailed using PDO:
$file = file_get_contents($somePathToUpload.$filename);
$pdo = new PDO("mysql:host=localhost;dbname=yourdb", "dbname", "dbpass");
$statement = $pdo->prepare("insert into upload_file(file_name) values(?)");
$statement->bindParam(1, $file);
$statement->execute();
also you can watch this video tutorial for more clearance
来源:https://stackoverflow.com/questions/49505557/save-generated-file-to-database-phpword