Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify .doc or .docx file in php

Tags:

php

tabs

I have to modify the uploaded .doc or .docx file in php. I googled but i only found how to read that but not as it is. I want the word file as it is and put text at the bottom of that MS Word file. How is this possible anyone know please reply.

Thanks,


I have used following code :-

$w='Test';
$fp = fopen('c:/text.doc', 'a+');
fwrite($fp, $w);
fclose($fp);

It appended the string but not showing in the word document. When i changed the extension of doc file to xml then it shows the string at the end. why should not it showing in doc file.

Thanks,

like image 529
Sachin Avatar asked Nov 28 '25 19:11

Sachin


2 Answers

For Docx files, you can easily use an zip reader such as TbsZip in order to read and edit the main XML sub-file (Docx files are actually zip archive files). For DOC files, it is very difficult because it is a binary file.

Here is an example of code with TbsZip:

<?php

$x = "Hello World!";

include_once('tbszip.php');

$zip = new clsTbsZip();

// Open the document
$zip->Open('mydoc.docx');
$content = $zip->FileRead('word/document.xml');
$p = strpos($content, '</w:body>');
if ($p===false) exit("Tag </w:body> not found in document.");

// Add the text at the end
$content = substr_replace($content, '<w:p><w:r><w:t>'.$x.'</w:t></w:r></w:p>', $p, 0);
$zip->FileReplace('word/document.xml', $content, TBSZIP_STRING);

// Save as a new file
$zip->Flush(TBSZIP_FILE, 'new.docx');
like image 89
Skrol29 Avatar answered Nov 30 '25 08:11

Skrol29


Documents in the DOCX format should be XML (zipped), so you can try to parse and modify them...

See here for details about the format.

like image 23
Macmade Avatar answered Nov 30 '25 09:11

Macmade



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!