在PHP中读取xls(Excel)文件

POG*_*OGI 2 php

我对此很新,所以我想问一个问题.我使用html上传了一个excel文件,当我尝试学习如何使用php读取excel文件时,这是我从IBM获得的:

<?php

$filename = basename($_FILES["file"]["name"]);

$ext = substr($filename, strrpos($filename, '.') + 1);

function get_data($qnum, $qtype, $qname, $qtext, $atext, $pcredit, $rcounts, $r, $qcount, $cfac, $sd, $disc_inx, $disc_coef)
{
    global $data;

    $data[] = array('QNum' => $qnum, 'Qtype' => $qtype, 'Questionname' => $qname, 'Questiontext' => $qtext,
        'Answertext' => $atext, 'PartialCredit' => $pcredit, 'RCounts' => $r, 'QCount' => $qcount,
        'Correctionfacility' => $cfac, 'DiscriminationIndex' => $disc_inx, 'DiscriminationCoefficient' => $disc_coef);
}

if ($ext == "xls") {
    $dom = DOMDocument::load($_FILES['file']['tmp_name']);
    $rows = $dom->getElementsByTagName('Row');
    $first_row = true;
    foreach ($rows as $row) {
        if (!$first_row) {
            $qnum = "";
            $qtype = "";
            $qname = "";
            $qtext = "";
            $atext = "";
            $pcredit = "";
            $r = "";
            $qcount = "";
            $cfac = "";
            $disc_inx = "";
            $disc_coef = "";

            $index = 1;
            $cells = $row->getElementsByTagName('Cell');
            foreach ($cells as $cell) {
                $ind = $cell->getAttribute('Index');
                if ($ind != null)
                    $index = $ind;

                if ($index == 1)
                    $qnum = $cell->nodeValue;
                if ($index == 2)
                    $qtype = $cell->nodeValue;
                if ($index == 3)
                    $qname = $cell->nodeValue;
                if ($index == 4)
                    $qtext = $cell->nodeValue;
                if ($index == 5)
                    $atext = $cell->nodeValue;
                if ($index == 6)
                    $pcredit = $cell->nodeValue;
                if ($index == 7)
                    $r = $cell->nodeValue;
                if ($index == 8)
                    $qcount = $cell->nodeValue;
                if ($index == 9)
                    $cfac = $cell->nodeValue;
                if ($index == 10)
                    $disc_inx = $cell->nodeValue;
                if ($index == 11)
                    $disc_coef = $cell->nodeValue;

                $index += 1;
            }
            get_data($qnum, $qtype, $qname, $qtext, $atext, $pcredit, $r, $qcount, $cfac, $disc_inx, $disc_coef);
        }
        $first_row = false;
    }
}

else {
    echo "Invalid file!";
}
?>
Run Code Online (Sandbox Code Playgroud)

我收到了语法错误

警告:DOMDocument :: load():期望开始标记,在/ tmp/phpwUIpyZ中找不到'<',第16行/var/www/moodle/question/upload_file.php中的第1行:致命错误:致电成员在第17行的/var/www/moodle/question/upload_file.php中的非对象上运行getElementsByTagName().

我的代码有什么错误?需要帮助,谢谢!

Sha*_*ali 5

Excel不是有效的DOMDocument,所以当然你不能使用DOMDocument :)

我建议使用像PHPExcelReader这样的东西.

祝你好运,
Shai.