PHP上传Word并读取显示

<?php

function test(){

    // 3, 调用文件上传函数
    $result = request()->file("story_img");;

// 4, 判断文件上传的结果
    if($result) {
        // 上传成功
        $imageUrl="./Public/Admin/images/images/";

        $zip = new \ZipArchive;
        $word=$zip->open('Uploads/'.$result);

        if($word==true){
            for ($i = 0; $i < $zip->numFiles; $i++) {
                /* 用zip压缩读取word中内容 */
                $zipElement = $zip->statIndex($i);

                /* 读取图片 */
                if (preg_match("([^\s]+(\.(?i)(jpg|jpeg|png|gif|bmp))$)", $zipElement['name'])) {
                    $rand = uniqid();
                    $file = "{$rand}.png";
                    $imageFile =$imageUrl. "{$file}";
                    $im = imagecreatefromstring($zip->getFromIndex($i));
                    //生成处理过图片,给模糊接口使用
                    $imWidth = imagesx($im);
                    $imHeight = imagesy($im);
                    if ($imWidth > 580) {
                        $fixWidth = 580;  //生成图片的固定宽度
                        $newHeight = intval($fixWidth / $imWidth * $imHeight);
                        $newIm = imagecreatetruecolor($fixWidth, $newHeight);
                        imagecopyresampled($newIm, $im, 0, 0, 0, 0, $fixWidth, $newHeight, $imWidth, $imHeight);  //调整图片大小
                        imagepng($newIm, $imageFile);  //生成图片
                        imagedestroy($im);
                        imagedestroy($newIm);
                    } else {
                        imagepng($im, $imageFile);  //生成图片
                        imagedestroy($im);
                    }
                    $a=$this->getFileName($zipElement['name']);

                    $existImages[$a] = '/Public/Admin/images/images/'.$file;
                } else {
                    //word内容,父级xml
                    if ($zipElement['name'] == "word/document.xml") {
                        $content .= $zip->getFromIndex($i);
                    }
                    //子级xml
                    if ($zipElement['name'] == "word/_rels/document.xml.rels") {
                        $childContent .= $zip->getFromIndex($i);
                    }
                }
            }
        }
        $zip->close();
        $zip = null;
        $documentContentFix = array('content' => $content, 'childContent' => $childContent, 'existImages' => $existImages);

        $content=$this->dealWithContent($documentContentFix);

        $pattern = '/<p(([\s\S])*?)<\/p>/';



        preg_match_all($pattern,$content,$info);

        foreach($info as $key => $value){

            $title[]=$value[0];
        }

        $title=$title['1'];
        $title=str_replace('>','',$title);

        $userinfo=session('user');
        $username=$userinfo['username'];



        $data=array(
            'filename'=>$result,
            'imagename'=>$file,
            'username'=>$username,
            'title'=>$title,
            'time'=>time());
        M('Fileload')->add($data);


        $this->ajaxReturn($content, 1, $_FILES['upfiledata']['name']);
    }else {
        // 上传失败
        echo 333;
        die;
    }

}



public  function dealWithContent($documentContentFix) {
    $childContent = $documentContentFix['childContent'];
    $existImages = $documentContentFix['existImages'];
    $content = $documentContentFix['content'];
    $search = array();
    $replace = array();

    //替换中出现图片位置
    preg_match_all('/<Relationship Id="(.*?)".*?Target="(.*?)"\/>/', $childContent, $matchs);
    $keys = $matchs['1'];  //id里面内容
    $values = $matchs['2'];  //word中资源位置及名称

    foreach ($keys as $key => $imageKey) {
        $imageArrayKey = $this->getFileName($values[$key]);
        //判断获取到的资源是否为图片,并且存在
        if (array_key_exists($key, $values) && array_key_exists($imageArrayKey, $existImages)) {
            $search[] = "<img>{$imageKey}</img>";
            $replace[] = "<img src='{$existImages[$imageArrayKey]}' />";
        }
    }

    //提取xml正文
  

    $content = preg_match("/<w:body>(.*?)<\/w:body>/", $content, $matches);
    $content = $matches['1'];
    $content = preg_replace('/<w:pPr>.*?<\/w:pPr>/', "", $content);
    $content = preg_replace('/<w:rPr>.*?<\/w:rPr>/', "", $content);
    $content = preg_replace('/<\/?w:r>|<\/?w:t>/', "", $content);
    $content = preg_replace('/<w:tcPr>.*?<\/w:tcPr>/', "", $content);
    $content = preg_replace('/<w:tblPrEx>.*?<\/w:tblPrEx>/', "", $content);
    $content = preg_replace('/(<\/w:p>)?<w:tc .*?>(<w:p>)?/', "<td>", $content);
    $content = preg_replace('/(<\/w:p>)?<(\/?)w:tc>(<w:p>)?/', "<$2td>\r\n", $content);
    $content = preg_replace('/<(\/?)w:tr .*?>/', "<$1tr>\r\n", $content);
    $content = preg_replace('/<(\/?)w:tr>/', "<$1tr>\r\n", $content);
    $content = preg_replace('/<w:p>/', "<p>", $content);
    $content = preg_replace('/<w:p .*?>/', "<p>", $content);
    $content = preg_replace('/<w:tbl .*?>/', "<table>", $content);
    $content = preg_replace('/<\/w:tbl>/', "</table>", $content);
    $content = preg_replace('/<\/w:p>/', "</p>\r\n", $content);
    $content = preg_replace('/<w:sectPr.*?>.*?<\/w:sectPr>/', "", $content);
    $content = preg_replace('/<w:drawing.*?>.*?<a:blip r:embed="(.*?)".*?<\/w:drawing>/', "<img>$1</img>", $content);
    $content = preg_replace('/<w:instrText.*?>.*?<\/w:instrText>/', "", $content);
    $content = preg_replace('/<\/?w:(.*?)\/?>/', "", $content);
    //var_dump($search);die;


    return str_replace($search, $replace, $content);  //替换图片位置
}


public function getFileName($file, $md5 = TRUE) {
    $fileName = basename($file);
    return $md5 ? md5($fileName) : $fileName;
}

 public function ajaxReturn($msg, $status = 0, $name = '') {

    echo json_encode(array('data' => $msg, 'status' => $status, 'name' => $name));
    exit();
}

 

上传Word文档读取其中的图片需要使用PHPWord和ZipArchive库。下面是一个简单的示例代码: ```php <?php require_once 'vendor/autoload.php'; use PhpOffice\PhpWord\IOFactory; if(isset($_FILES['wordDoc'])) { $errors= array(); $file_name = $_FILES['wordDoc']['name']; $file_size = $_FILES['wordDoc']['size']; $file_tmp = $_FILES['wordDoc']['tmp_name']; $file_type = $_FILES['wordDoc']['type']; $file_ext = strtolower(end(explode('.',$_FILES['wordDoc']['name']))); $extensions = array("doc","docx"); if(in_array($file_ext,$extensions) === false){ $errors[] = "extension not allowed, please choose a Word document file."; } if($file_size > 2097152) { $errors[] = 'File size must be less than 2 MB'; } if(empty($errors) == true) { $outputDir = "uploads/"; $outputFile = $outputDir . $file_name; move_uploaded_file($file_tmp, $outputFile); $phpWord = IOFactory::load($outputFile); $zip = new ZipArchive; if ($zip->open($outputFile) === TRUE) { for ($i = 0; $i < $zip->numFiles; $i++) { $zipEntryName = $zip->getNameIndex($i); if (strpos($zipEntryName, 'media') !== false) { $imageContent = $zip->getFromName($zipEntryName); $imageType = exif_imagetype('data://image/jpeg;base64,' . base64_encode($imageContent)); $imageFileName = basename($zipEntryName); file_put_contents($outputDir . $imageFileName, $imageContent); echo "<img src='$outputDir$imageFileName' alt='Word Image'/>"; } } $zip->close(); } } else { print_r($errors); } } ?> <form action="" method="POST" enctype="multipart/form-data"> <input type="file" name="wordDoc" /> <input type="submit"/> </form> ``` 上面的代码假设您已经创建了一个名为“uploads”的文件夹来存储上传的文件和图片。请注意,如果Word文档中有多个图片,请根据需要进行调整。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值