Search code examples
phpvbacom

php replace text in msword using COM


I'm trying to use php replace texts in msword doc. Using COM. throws Error [0x80020011] Does not support a collection. code is copy and modified from VBA.

       $word = new COM("Word.Application") or die("Word not installed!");
        try{
            $word->Documents->Open("c:\1.doc");
            $word->ActiveDocument->Range->Find->Text="222";
            $word->ActiveDocument->Range->Find->Replacement->Text="111";
            $word->ActiveDocument->Range->Find->Forward=True;
            //$word->ActiveDocument->Range->Find->Replace=2;
            //$word->ActiveDocument->Range->Find->Wrap=1;
            $word->ActiveDocument->Range->Find->Format=False;
            $word->ActiveDocument->Range->Find->MatchCase=False;
            $word->ActiveDocument->Range->Find->MatchWholeWord=False;
            $word->ActiveDocument->Range->Find->MatchWildcards=False;
            $word->ActiveDocument->Range->Find->MatchSoundsLike=False;
            $word->ActiveDocument->Range->Find->MatchAllWordForms=False;
            $word->ActiveDocument->Range->Find->Execute();
            $word->ActiveDocument->SaveAs("c:\2.doc");
            $word->Quit();
       }
       .....

another way

   $wdFindContinue = 1;
   $wdReplaceAll = 2;
   $word->ActiveDocument->Content->Find->Execute("222", false, false, false, false, false, true, $wdFindContinue, false, "111", $wdReplaceAll);

the server is using office 2007, and php 4.6 /apache 2.1


Solution

  • update:

    Do not use it in php , it won't replace all the strings.

    another solution:

    1. save word as xml
    2. then use php fread to open it as text
    3. replace strings inside.

    and save to file.