0

I want to replace multiple words in my docx-file. I used the words from the input-elements and I pass them through the 'POST'-method. I already replaced the '$bedrijfsnaam' but I want to add more str replacements. I created '$newContents2' but as I thought, it didn't work. How can I solve this? Do I have to add another 'oldContents' like 'oldContents2'?

$bedrijfsnaam = $_POST['bedrijfsnaam'];
$offertenummer = $_POST['offertenummer'];
$naam = $_POST['naam'];

$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
$wordDoc = "Document.docx";
$newFile = $offertenummer . ".docx";

copy("Document.docx", $newFile);

if ($zip->open($newFile) === TRUE) {

    $oldContents = $zip->getFromName($fileToModify);

    $newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);

    $newContents2 = str_replace('$naam', $naam, $oldContents);

    $zip->deleteName($fileToModify);

    $zip->addFromString($fileToModify, $newContents);


    $return =$zip->close();
    If ($return==TRUE){
        echo "Success!";
    }
} else {
    echo 'failed';
}

$newFilePath = 'offerte/' . $newFile;

$fileMoved = rename($newFile, $newFilePath);
2
  • 1
    '$bedrijfsnaam' is that literal value, dont quote variables. You can use arrays for the search and replace values, see the manual (php.net/manual/en/function.str-replace.php). Commented Jul 6, 2017 at 19:37
  • Also be careful about the dollar sign in double-quoted strings - php will try to parse the variables and replace the text with the variable (php.net/manual/en/…) Commented Jul 6, 2017 at 19:46

1 Answer 1

1

You're going to want to keep editing the same content.

$newContents = str_replace('$bedrijfsnaam', $bedrijfsnaam, $oldContents);

The result of the first replacement is in $newContents, so if you want to build upon that, you need to replace the second string in $newContents and store the result in $newContents, which now contains the result of both string replacements.

$newContents = str_replace('$naam', $naam, $newContents);

Edit: Better yet, you can just use arrays and do it all in one line

$newContent = str_replace(
    ['$bedrijfsnaam', '$naam'],
    [ $bedrijfsnaam, $naam], 
    $oldContents
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.