RH

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

add a comment
0

25 Answers

  • Votes
  • Oldest
  • Latest
TA

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

<?
	$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);
?>
add a comment
0
RH

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

add a comment
0
AL

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.

add a comment
0
VI

any1 plz tel how to use images on the ord document generated using PHP

add a comment
0
PU

Hello
i reach the problem
I don't know how do i change the page size of microsoft word(like A4,A5 ,...) with PHP?

add a comment
0
PA

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:

 
    $fp = fopen("Passes.doc", 'w+'); 
    foreach($pass_arry as $pass_arry) 
    {
        $pass_arry = $pass_arry."\n";
        fwrite($fp, $pass_arry);
    }
    fclose($fp);
 

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!

add a comment
0
TH
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>";

HOW CAN I CREATE A NEW SLIDE IN THE POWER POINT USING THIS CODE ???

add a comment
0
D1

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:

<?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;

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?

add a comment
0
SD

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

add a comment
0
AN

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.

add a comment
0
MA

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

$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;

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!

add a comment
0
GR

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

add a comment
0
GR

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

add a comment
0
ST

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.

add a comment
0
TR

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).

add a comment
0
ST

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

add a comment
0
TR

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?

add a comment
0
ST

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.
plz help

add a comment
0
TR

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

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

You really should read up on PHP if you're going to be using it.

add a comment
0
ST

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

add a comment
0
AR

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");

add a comment
0
BL

the exact error I get is "The document file or path is not valid...."

add a comment
0
BL

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?

add a comment
0
GI

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 :

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>";

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.)

add a comment
0
WA

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:

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 );

}
add a comment
0