2011-09-19 110 views
2

我对此很新,所以我想问一个问题。我使用HTML上传Excel文件,当我尝试学习如何使用PHP来读取Excel文件,这是我从IBM得到:在PHP中读取xls(Excel)文件

<?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!"; 
} 
?> 

而且我得到了一个语法错误

Warning: DOMDocument::load(): Start tag expected, '<' not found in /tmp/phpwUIpyZ, line: 1 in /var/www/moodle/question/upload_file.php on line 16 Fatal error: Call to a member function getElementsByTagName() on a non-object in /var/www/moodle/question/upload_file.php on line 17.

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

回答

5

Excel是不是一个有效的DOM文档,所以当然你不能使用DOM文档吧:)

我会建议使用的东西准备好,如PHPExcelReader

祝您好运,
Shai。

+0

非常感谢! :d – POGI

1

由于错误消息说,$dom is a non-object - 换句话说,DOMDocument::load返回东西,但不是一个对象。有可能是各种原因,但最有可能的是:

  • 文件不存在或无法读取
  • 文件格式不正确(不是有效的DOM文档),分析失败

请参阅手册:http://php.net/manual/en/domdocument.load.php

还要注意,您似乎试图将XLS文件解析为DOM文档 - 不会飞,这是完全不同的文件格式。