Hello,
If it's working standalone but not when adding other PHP code, the most common issue is that the web server or PHP response is adding some string to the DOCX. For example some information from HTML or some response from a framework or CMS. We have run your script on our test servers and all of them are working correctly and the DOCX output is not corrupted.
Some old posts talk about this question:
https://www.phpdocx.com/en/forum/default/topic/347
https://www.phpdocx.com/en/forum/default/topic/1508
https://www.phpdocx.com/en/forum/default/topic/1463
The first two needed to use the ob_clean PHP function and the third topic was solved fixing the response of the framework that as being used wrongly. They talk about the createDocxAndDownload method, but it's the same case.
To find out the source of the problem we recommend you to compare both DOCX (with and without the stream mode) using a HEX viewer. The corrupted one will have more strings with the extra information that is being added.
We also recommend you run the same script using PHP CLI mode to check the output and find if the web server or PHP are adding the extra contents to the DOCX:
$ php script.php > document.docx
About the createDocxAndDownload method, it will always generate the file in the fs. You can remove the DOCX after the document is generated and downloaded setting the removeAfterDownload option to true (https://www.phpdocx.com/api-documentation/layout-and-general/create-and-download-docx-with-PHP).
Regards.