Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

fwrite-ing an RTF

Status
Not open for further replies.

DeepBlerg

Technical User
Jan 13, 2001
224
0
0
AU
Hi,

I am trying to open an RTF and then change values in the document. I've created an RTF file in MS Word adn included the text "((data1))", which hopefully PHP should replace with "test words from PHP".

Problem is, using the w+ mode when fopen-ing creates a blank 0kb file and in r+ mode, it copies the RTF source and pastes it to the end of the document which is not what I want.

Heres the PHP, any ideas?

$filename = "template.rtf";
$fd = fopen ($filename , "w+");
$fdContents = fread ($fd, filesize ($filename));
$badStr = "((data1))";
$goodStr = "test words from PHP";
$fdContents = preg_replace($badStr, $goodStr, $fdContents);
fwrite($fd, $fdContents);
fclose ($fd);

Thanks.
 

Try str_replace instead...

eg:

$fdContents = str_replace ($badStr, $goodStr, $fdContents);

Hope this helps,

Emma
 

Here is an example that may be useful...

$filename = file.rtf";
if(!($fp= fopen ($filename, "r"))) die ("Can't open file 1");
$Contents = file_get_contents($filename);
fclose ($fp);

//Replacefields
$newContents = str_replace ($badstring, $godstring, $Contents);


// re-save the file as an rtf
$saveFile = "new_filename.rtf";

if(!($fq= fopen ($saveFile, "w+"))) die ("Can't open file 2");
fwrite ($fq, $newContents);
fclose ($fq);

Emma
 
Emma is right on. The key is to read the contents from the file, then either close the file and reopen it or seek back to the beginning of the file.

Though it is short sighted to assume you can always hold the contents of the entire file in memory, and a little wasteful of resources. Better and safer might be to open a tempfile for writing, read from the original writing to the tempfile, then when you operation is successful close both files and rename the temp to the original.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top