2011-09-19 106 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文檔 - 不會飛,這是完全不同的文件格式。