PHP Create Word Document

  • rinto_harianja
  • Beginner
  • Beginner
  • User avatar
  • Posts: 45
  • Loc: Jakarta

Post 3+ Months Ago

Dear All,

I want to create report in Word Document with PHP and database MySQL.
Anyone have example to write Word Document Using PHP?

Thansk


Rinto H
  • Tannu4u
  • Proficient
  • Proficient
  • User avatar
  • Posts: 480
  • Loc: India

Post 3+ Months Ago

Here is the simplest method to write to a word file:

PHP Code: [ Select ]
<?
 
   $fp = fopen("amit.doc", 'w+');
 
   $str = "<B>This is the text for the word file created through php programming</B>";
 
 
 
   fwrite($fp, $str);
 
 
 
   fclose($fp);
 
?>
  1. <?
  2.  
  3.    $fp = fopen("amit.doc", 'w+');
  4.  
  5.    $str = "<B>This is the text for the word file created through php programming</B>";
  6.  
  7.  
  8.  
  9.    fwrite($fp, $str);
  10.  
  11.  
  12.  
  13.    fclose($fp);
  14.  
  15. ?>




if the above code is not enough then go to

http://www.programmershelp.co.uk/phpcreateword.php
  • rinto_harianja
  • Beginner
  • Beginner
  • User avatar
  • Posts: 45
  • Loc: Jakarta

Post 3+ Months Ago

I have PHP create excel file like this:
<?php
$word = new COM("word.application") or die ("couldnt create an instance of word");
echo "loaded , word version{$word->version}";
//bring word to the front
$word->visible = 1;
//open a word document
$word->Documents->Add();
//add some text to the document
$word->Selection->TypeText("this is some sample text in the document");
//save the document as sampleword.doc
$word->Documents[1]->SaveAs("sampleword.doc");
//close word
$word->Quit();
//free object resources
$word->Release();
$word = null;
?>


But i want to format the content of Text. I want to change align, valign, and etc.
How i do this?

Thanks

Rinto H
  • gisele
  • Expert
  • Expert
  • User avatar
  • Posts: 585
  • Loc: Nimes (France)

Post 3+ Months Ago

Hi,

Tannu4u was right, you can create .doc files just with fopen() , naming it file_name.doc and putting in some html source and it works.
To me it's far easier than using COM libraries.

You can also create Excel file or any open office doc file just writing in some html souce and giving the right extention.

You could also change the current document into a word file or a Excel file, no need to fopen and fputs try this simple test script to understand what I mean and check what does it look like :
PHP Code: [ Select ]
 
header("Content-Type: application/vnd.ms-excel");
 
print "<table border=\"1\"><tr><td><b>field1</b></td><td><b>field2</b></td></tr>";
 
print "<tr><td>value1 </td><td bgcolor=\"#137799\">value2 in blue cell bakground</td></tr></table>";
 
 
  1.  
  2. header("Content-Type: application/vnd.ms-excel");
  3.  
  4. print "<table border=\"1\"><tr><td><b>field1</b></td><td><b>field2</b></td></tr>";
  5.  
  6. print "<tr><td>value1 </td><td bgcolor=\"#137799\">value2 in blue cell bakground</td></tr></table>";
  7.  
  8.  


of course if you do a word file set the content-type to "application/msword" in header().
And do what you want for the page setting with html code (bgcolor, tables, align , etc.)
  • bluephoenix66
  • Born
  • Born
  • bluephoenix66
  • Posts: 2
  • Loc: London

Post 3+ Months Ago

I have an e-commerce website and I am trying to have a webpage create a .doc or .rtf document to print labels based on the customers' addresses in a mysql database.

For this reason, I need to create a document based on a labels template.

I have saved the labels template as whslabels.rtf on the website, and on every label I have written "Address1", "Address2", "Address3", ... then I have the mentioned webpage do a str_replace replacing the "Address..." words with the customer's address, and then save this to a new file named "newlabels6.rtf".

$template_file = "whslabels.rtf";
$handle = fopen($template_file , "r");
$contents = fread($handle, filesize($template_file));

$original= array("Address1", "Address2");
$new = array("pizza", "beer");

$newphrase = str_replace($original, $new, $contents);

$handle2 = fopen("newlabel6.rtf" , "w");

fwrite ( $handle2 ,$newcontents);
fclose ($handle);
fclose($handle2);

but when I go to open the new .rtf file it doesn't seem to able to open it.

What am I doing wrong?
  • bluephoenix66
  • Born
  • Born
  • bluephoenix66
  • Posts: 2
  • Loc: London

Post 3+ Months Ago

the exact error I get is "The document file or path is not valid...."
  • azhaz_ri
  • Born
  • Born
  • azhaz_ri
  • Posts: 1
  • Loc: Malaysia

Post 3+ Months Ago

try put this code at in your code..
header("Content-Type: application/vnd.ms-word");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=test.doc");
  • studentpk
  • Born
  • Born
  • studentpk
  • Posts: 4

Post 3+ Months Ago

Hi
i need some help
i want to edit a word file using php
means i want to search a word and replace it with another using php.
looking forword for ur replies
  • Truce
  • Guru
  • Guru
  • Truce
  • Posts: 1477
  • Loc: Washington DC

Post 3+ Months Ago

Please don't bring up really old threads, especially if they aren't the same issue you're having.

To answer your question, http://www.php.net/str_replace

You really should read up on PHP if you're going to be using it.
  • studentpk
  • Born
  • Born
  • studentpk
  • Posts: 4

Post 3+ Months Ago

Sorry dear.
i did use str_replace

check out the code


<?PHP
$filename = "c:/PHP.doc";

$f="c:/d.doc";
$fp = fopen($f, 'wb');
$fp_temp = fopen($filename, 'rb');


$old_contents = fread ( $fp_temp, filesize ($filename));
fclose ( $fp_temp);
echo $old_contents;
$constants=str_replace("PHP","PHP1",$old_contents);
fwrite($fp, $constants);
fclose($fp);
?>

but by this file d.doc did not open in word and that is the main problem at my end.
please help
  • Truce
  • Guru
  • Guru
  • Truce
  • Posts: 1477
  • Loc: Washington DC

Post 3+ Months Ago

Well, what is happening when you try to open the resulting file in Word? Is PHP.doc a valid Word document? Have you attempted to compare the two documents (PHP.doc and d.doc) in a Hex editor to see what changes where made?
  • studentpk
  • Born
  • Born
  • studentpk
  • Posts: 4

Post 3+ Months Ago

it simply did not opem and shows an error.

well i did not use and editor to compare
but PHP.doc shows size of 24kb but d.doc shows 25kbs
  • Truce
  • Guru
  • Guru
  • Truce
  • Posts: 1477
  • Loc: Washington DC

Post 3+ Months Ago

Well, if you really want us to help you are going to need to give us some more info here. Unfortunately, we can't read minds, and it's illegal for me to hack into your computer, regardless of what my intent is.

So tell us what the error is. Post both of the files for us to review (like, upload them via FTP in binary mode and give us links).
  • studentpk
  • Born
  • Born
  • studentpk
  • Posts: 4

Post 3+ Months Ago

Hi

i reach the problem.
well when i try to replace a word with equal number of charchters. it works fine. but when i try to replace with bigger word it didnt open in the word.

means if replace PHP with HPP it will work
but if try to replace PHP with PHP1 it will not.

this might help you to solve the problem

thanks.
  • gregcaulder
  • Born
  • Born
  • gregcaulder
  • Posts: 3

Post 3+ Months Ago

rinto_harianja wrote:
I have PHP create excel file like this:
<?php
$word = new COM("word.application") or die ("couldnt create an instance of word");
echo "loaded , word version{$word->version}";
//bring word to the front
$word->visible = 1;
//open a word document
$word->Documents->Add();
//add some text to the document
$word->Selection->TypeText("this is some sample text in the document");
//save the document as sampleword.doc
$word->Documents[1]->SaveAs("sampleword.doc");
//close word
$word->Quit();
//free object resources
$word->Release();
$word = null;
?>


But i want to format the content of Text. I want to change align, valign, and etc.
How i do this?

Thanks

Rinto H


Ok i have code exactley like this but for creating a word document. The problem im having is that I get a fat error on this line "$word->Selection->TypeText("this is some sample text in the document");"

Any suggestions. It seems that I cant add anything to the document.

I have a similar script to open a template, but it ALWAYS says that it cant find the blasted file, not matter what I try ot use for the location of the file.

Can anyone help me with that at all?

Greg
  • gregcaulder
  • Born
  • Born
  • gregcaulder
  • Posts: 3

Post 3+ Months Ago

I have gotten my code above to work correctly. No problems their anymore. What i am having a problem with is being able to insert an image from a URL into the file itself. how would i go about doing that?


Greg
  • Denis Slaveckij
  • Born
  • Born
  • Denis Slaveckij
  • Posts: 1

Post 3+ Months Ago

I think it's better use rtf format. Look at <a href="http://www.phprtf.com">http://www.phprtf.com</a>.
  • masterblue
  • Born
  • Born
  • masterblue
  • Posts: 1

Post 3+ Months Ago

Hi, I tried the code below to make a word document.

Code: [ Select ]
$word = new COM("word.application") or die ("couldnt create an instance of word");
echo "loaded , word version{$word->version}";
//bring word to the front
$word->visible = 1;
//open a word document
$word->Documents->Add();
//add some text to the document
$word->Selection->TypeText("this is some sample text in the document");
//save the document as sampleword.doc
$word->Documents[1]->SaveAs("sampleword.doc");
//close word
$word->Quit();
//free object resources
$word->Release ();
$word = null;
  1. $word = new COM("word.application") or die ("couldnt create an instance of word");
  2. echo "loaded , word version{$word->version}";
  3. //bring word to the front
  4. $word->visible = 1;
  5. //open a word document
  6. $word->Documents->Add();
  7. //add some text to the document
  8. $word->Selection->TypeText("this is some sample text in the document");
  9. //save the document as sampleword.doc
  10. $word->Documents[1]->SaveAs("sampleword.doc");
  11. //close word
  12. $word->Quit();
  13. //free object resources
  14. $word->Release ();
  15. $word = null;


What I get is an error :
-----------------------------------------------------------------
Fatal error: Uncaught exception 'com_exception' with message 'Error [0x80020003] Kan lid niet vinden. ' in D:\xampp\htdocs\basiccv\Maakpdf.php:42 Stack trace: #0 D:\xampp\htdocs\basiccv\Maakpdf.php(42): com->Release() #1 {main} thrown in D:\xampp\htdocs\basiccv\Maakpdf.php on line 42
-----------------------------------------------------------------

I Checked the documentation and I saw that the Release function is for PHP 5.X
I Use PHP Version 5.2.3
So the version is right.

Is RELEASE the line were you have to put the directory in?

Can someone help me with an understanable sollution?

Thanks!
  • anirban
  • Born
  • Born
  • anirban
  • Posts: 1

Post 3+ Months Ago

Hi ,

When I am running the code:

<?php
$word = new COM("word.application");

$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '2"';
$word->Selection->PageSetup->RightMargin = '2"';

//Setup the font
$word->Selection->Font->Name = 'Verdana';
$word->Selection->Font->Size = 8;

//Write some text
$word->Selection->TypeText("This is a test document");
//Save the document as DOC file
$word->Documents[1]->SaveAs("D:\\Domains\\jobgool.com\\wwwroot\\makeresume\\testdoc.doc");

//quit and release COM resources
$word->quit();
$word->Release();
$word = null;

?>


I am getting the following error:

Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `word.application': Invalid syntax ' in D:\Domains\xxxxxx.com\wwwroot\makeresume\testdoc.php:2 Stack trace: #0 D:\Domains\xxxxxx.com\wwwroot\makeresume\testdoc.php(2): com->com('word.applicatio...') #1 {main} thrown in D:\Domains\xxxxxx.com\wwwroot\makeresume\testdoc.php on line 2

Can someone provide me any suggestion of code modification?

Thanks in advance
Anirban.
  • sejpal_dipesh
  • Born
  • Born
  • sejpal_dipesh
  • Posts: 1

Post 3+ Months Ago

hi

I am using the following code
<?php
$word = new COM("word.application") or die ("couldnt create an instance of word");
echo "loaded , word version{$word->version}";
//bring word to the front
$word->visible = 1;
//open a word document
$word->Documents->Add();
//add some text to the document
$word->Selection->TypeText("this is some sample text in the document");
//save the document as sampleword.doc
$word->Documents[1]->SaveAs("sampleword.doc");
//close word
$word->Quit();
//free object resources
$word->Release();
$word = null;
?>

but i m getting following error while running this code on the server

Fatal error: Class 'COM' not found in file.php on line 24

Please help me as soon as possible

Thank you
  • D1N0
  • Newbie
  • Newbie
  • D1N0
  • Posts: 5

Post 3+ Months Ago

So using the methods described so far i have been able to create my word document. Thank you. So much easier. But now it doesn't close the file. It puts the next echo statement that i am using to test the results of the form data that will be going into the word document. I don't know where i am going wrong?
here is the code:
Code: [ Select ]
<?php
//-----This Sections is all of the data for the request email----
 
//Get Data from the Form
 
$from = $_POST['email'];
$company = $_POST['company'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$phone = $_POST['phonenumber'];
$software = $_POST['program'];
$version = $_POST['version'];
$sr = $_POST['sr'];
$filename = sprintf("2-%10s.doc",$sr);
$srnumber = sprintf ("2-%10s", $sr);
 
$string =
 
header("Content-Type: application/vnd.ms-word");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=$filename");
 
echo (" Fist Name: $firstname
    Last Name: $lastname
    Company:   $company
    Phone:     $phone
    From:      $from
    Software:  $software
    Version:   $version
    SR Number: $srnumber
    ");
 
$echo_string = "
    Fist Name: &nbsp $firstname<br />
    Last Name: &nbsp $lastname<br />
    Company: &nbsp $company<br />
    Phone:&nbsp $phone<br />
    From: &nbsp $from <br />
    Software: &nbsp $software<br />
    Version: &nbsp $version<br />
    Request: &nbsp $srnumber<br />
    File Name: &nbsp $filename<br />";
 
echo $echo_string;
  1. <?php
  2. //-----This Sections is all of the data for the request email----
  3.  
  4. //Get Data from the Form
  5.  
  6. $from = $_POST['email'];
  7. $company = $_POST['company'];
  8. $firstname = $_POST['firstname'];
  9. $lastname = $_POST['lastname'];
  10. $phone = $_POST['phonenumber'];
  11. $software = $_POST['program'];
  12. $version = $_POST['version'];
  13. $sr = $_POST['sr'];
  14. $filename = sprintf("2-%10s.doc",$sr);
  15. $srnumber = sprintf ("2-%10s", $sr);
  16.  
  17. $string =
  18.  
  19. header("Content-Type: application/vnd.ms-word");
  20. header("Expires: 0");
  21. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  22. header("content-disposition: attachment;filename=$filename");
  23.  
  24. echo (" Fist Name: $firstname
  25.     Last Name: $lastname
  26.     Company:   $company
  27.     Phone:     $phone
  28.     From:      $from
  29.     Software:  $software
  30.     Version:   $version
  31.     SR Number: $srnumber
  32.     ");
  33.  
  34. $echo_string = "
  35.     Fist Name: &nbsp $firstname<br />
  36.     Last Name: &nbsp $lastname<br />
  37.     Company: &nbsp $company<br />
  38.     Phone:&nbsp $phone<br />
  39.     From: &nbsp $from <br />
  40.     Software: &nbsp $software<br />
  41.     Version: &nbsp $version<br />
  42.     Request: &nbsp $srnumber<br />
  43.     File Name: &nbsp $filename<br />";
  44.  
  45. echo $echo_string;


It takes the formdata and uses it to create the filename, and the contents, but it adds the $echo_string to the document as well. Any ideas?
  • thumrith
  • Born
  • Born
  • thumrith
  • Posts: 1

Post 3+ Months Ago

PHP Code: [ Select ]
header("Content-Type: application/vnd.mspowerpoint");
print "<table border=\"1\"><tr><td><b>field1</b></td><td><b>field2</b></td></tr>";
print "<tr><td>value1 </td><td bgcolor=\"#137799\">value2 in blue cell bakground</td></tr></table>";
 
  1. header("Content-Type: application/vnd.mspowerpoint");
  2. print "<table border=\"1\"><tr><td><b>field1</b></td><td><b>field2</b></td></tr>";
  3. print "<tr><td>value1 </td><td bgcolor=\"#137799\">value2 in blue cell bakground</td></tr></table>";
  4.  


HOW CAN I CREATE A NEW SLIDE IN THE POWER POINT USING THIS CODE ???
  • Pado
  • Born
  • Born
  • Pado
  • Posts: 1

Post 3+ Months Ago

Hey, thanks for the help. This was very helpful. I was quickly able to create a word document with PHP. I used the following code:
PHP Code: [ Select ]
 
    $fp = fopen("Passes.doc", 'w+');
    foreach($pass_arry as $pass_arry)
    {
        $pass_arry = $pass_arry."\n";
        fwrite($fp, $pass_arry);
    }
    fclose($fp);
 
  1.  
  2.     $fp = fopen("Passes.doc", 'w+');
  3.     foreach($pass_arry as $pass_arry)
  4.     {
  5.         $pass_arry = $pass_arry."\n";
  6.         fwrite($fp, $pass_arry);
  7.     }
  8.     fclose($fp);
  9.  

It worked great, but I have a slight problem. When word opens up, I get another window that says "File Conversion-Passes1.doc. Select the encoding that makes your document readable. Text coding: Windows(default) blah blah" and I have to press "okay" for it to open. Is there anyway I can make it so this window doesn't pop up and the Word document opens immediately? Thanks!
  • purya
  • Born
  • Born
  • purya
  • Posts: 1

Post 3+ Months Ago

Hello
i reach the problem
I don't know how do i change the page size of microsoft word(like A4,A5 ,...) with php?
  • Vinita
  • Born
  • Born
  • Vinita
  • Posts: 1

Post 3+ Months Ago

any1 please tel how to use images on the ord document generated using php
  • Almaron
  • Born
  • Born
  • Almaron
  • Posts: 1

Post 3+ Months Ago

Hi.
Got another quiz.
What I have:
1. .doc file named "parse.doc" with placeholders like [+key+]
2. an array called $tmp like this $tmp[key]=value
3. a name for a new file $fname;

What I need to do:
1. Take the contents of parse.doc and replace placeholders with values from the array and then put the text into a new file called $fname.doc

Tried to parse it using str_replace and preg_replace (POSIX regular), but had no luck. Does anybody have suggestions?
P.S. COM does not work. It's CentOS server.

P.P.S. Problem solved using ZipArchieve class to parse the docx document.
  • walkerstone
  • Born
  • Born
  • walkerstone
  • Posts: 1

Post 3+ Months Ago

Sorry to ressurect a very dead thread. Just adding this in the hope it helps anyone that has a problem like this in future as this returned high in the rankings.

An easy way to generate word documents without going to the lengths of COM libraries is to use the FILE_PUT_CONTENTS.

Here's a little function I use to spew out a simple replace on my template. It's fairly limited in use but can be improved upon. A working base at least:

Code: [ Select ]
function generateDocsFromTemplate( $templatePath, $newFileName, $stringToReplace, $replacementString ){

    $template = fopen($templatePath, "r");
    $contents = fread($template, filesize($templatePath));

    // This block takes care of matching the length mismatch
    // Always make sure the replacement code in the template
    // is longer than the new string.
    $clientCodeLength = strlen($clientCode);
    $replacementLength = strlen($stringToReplace);
    $difference = $replacementLength - $clientCodeLength;

    for( $i=0; $i<$difference; $i++ ) {
        $clientCode .= chr(0);
    }

    $newcont = str_replace( $stringToReplace, $replacementString, $contents );

    $outputFileName = $newFileName . '.doc'; // Extension can be (.docx)

    file_put_contents( $outputFileName, $newcont);

    fclose( $template );

}
  1. function generateDocsFromTemplate( $templatePath, $newFileName, $stringToReplace, $replacementString ){
  2.     $template = fopen($templatePath, "r");
  3.     $contents = fread($template, filesize($templatePath));
  4.     // This block takes care of matching the length mismatch
  5.     // Always make sure the replacement code in the template
  6.     // is longer than the new string.
  7.     $clientCodeLength = strlen($clientCode);
  8.     $replacementLength = strlen($stringToReplace);
  9.     $difference = $replacementLength - $clientCodeLength;
  10.     for( $i=0; $i<$difference; $i++ ) {
  11.         $clientCode .= chr(0);
  12.     }
  13.     $newcont = str_replace( $stringToReplace, $replacementString, $contents );
  14.     $outputFileName = $newFileName . '.doc'; // Extension can be (.docx)
  15.     file_put_contents( $outputFileName, $newcont);
  16.     fclose( $template );
  17. }

Post Information

  • Total Posts in this topic: 27 posts
  • Users browsing this forum: No registered users and 49 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.