如何使用str_replace()函数从php中的excel文件替换占位符?

时间:2017-06-16 13:06:51

标签: php excel str-replace docx

以下PHP代码完全适用于word文档(特别是 .docx ),但对于excel( .xlsx ),它不会更改占位符。据我所知,这段代码将word文件转换为document.xml文件,并在zip文件的word文件夹中找到{{placeholder}}并将其更改为我们想要的文本。

    if(isset($_POST["e_submit"]))
    {
        $name=(string) $_POST["e_name"];
        $email=(string) $_POST["e_email"];
        $source='TemplateSimpleText.docx';
        $temp='template'.'.docx';

        copy($source,$temp);

        $zip = new ZipArchive;

        $fileXml='word/document.xml';
        if($zip->open($temp) === TRUE)
        {
            $old=$zip->getFromName($fileXml);

            $new=str_replace('{{Name}}',$name,$old);
            $new=str_replace('{{Email}}',$email,$new);

            $zip->deleteName($fileXml);
            $zip->addFromString($fileXml,$new);
            $zip->close();

            if (ob_get_level()) {
                ob_end_clean();
            }

            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($temp));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($temp));


            readfile($temp);
            unlink($temp);

           exit();
        }
    }

0 个答案:

没有答案