PHP word导入题库

public function index()
    {
        $url = public_path()."static/word.docx";
        $word_obj = new PhpWord();
        $sections = IOFactory::load($url)->getSections();
        $arr = [];
        foreach ($sections as $key => $val){
            $elements = $val->getElements();
            foreach ($elements as $k => $v){
                if($v instanceof TextRun){
                    $str = "";
                    $content_elements = $v->getElements();
                    foreach ($content_elements as $k1 => $v1){
                        if($v1 instanceof Text){
                            mb_convert_encoding($v1->getText(), 'UTF-8');
                            $str .=  $v1->getText();

                        }elseif ($v1 instanceof Image){
                            $imageDataTmp = $v1->getImageStringData(true);
                            $imageType = $v1->getImageType() ? $v1->getImageType() : 'image/jpg';
                            $imageData = 'data:' . $imageType . ';base64,' . str_replace(array("\r\n", "\r", "\n"), "", $imageDataTmp);
                            $imageSrc = './static/uploads/' . md5($v1->getSource()) . '.' . $v1->getImageExtension();
                            file_put_contents($imageSrc,base64_decode(explode(',',$imageData)[1]));
                            $str .= '<img src="'. $imageSrc .'" style="width:100%;height:auto">';
                        }
                    }
                    //echo $str."\n";
                    $first_str = mb_substr( $str, 0, 1, "UTF-8" );
                    if(preg_match("/^\d*$/",$first_str)){ //是数字
                        $temp = [];
                        $temp['title'] = $str; //题干
                    }elseif (preg_match('/[a-zA-Z]/',$first_str)){ //是字母
                        $temp['options'][] = $str; //选项
                    }else{ //是中文
                        $two_str = mb_substr( $str, 0, 2, "UTF-8" );
                        switch ($two_str){
                            case "答案":
                                $temp['aswer'] = $str;
                                break;
                            case "难度":
                                $temp['difficulty'] = $str;
                                break;
                            case "解析":
                                $temp['parse'] = $str;
                                array_push($arr,$temp);
                        }
                    }
                }

            }
        }
        print_r($arr);
    }

必须按照模板规则

posted @ 2021-04-08 18:13  FinnYY  阅读(671)  评论(1编辑  收藏  举报