2013-08-27 219 views
1

我是一個非常新的PHP。有些人可以解決我的問題嗎?讀取CSV文件時出錯

當我嘗試在Windows中使用xampp執行時,以下代碼工作得非常好。但是當我嘗試通過ssh終端執行時,它不適用於Ubuntu。

以下是php警告。但是當我試圖在Windows上,它工作正常在CSV中的所有記錄(這讓我插入或更新語句在CSV每條記錄)

PHP的警告:FEOF()預計參數1是資源,布爾在/ home/myetexts/Documents/code/Pearson/test2.php在線8
PHP警告:fgetcsv()期望參數1是資源,布爾//.PHP第9行

<?php 
    ini_set('max_execution_time', 10000); 
    $file = fopen('NZ_Price_list.csv', 'r'); 
    $count = 0; 
    $con=mysql_connect("localhost","root",""); 
    mysql_select_db('newlocalabc'); 

    while(!feof($file)){ 
     $record = fgetcsv($file); 
     if(!empty($record[0])){ 
      // echo 'ISBN: '.$record[0].'<br />'; 
     $price =round(($record[11])/0.85,2); 
     if($record[3]== "Higher Education" || $record[3] == "Vocational Education"){ 
      $price =round((($record[11])/0.85)/0.97,2); 
     } 
     $sql = 'SELECT * FROM `products` WHERE `isbn` = '.$record[0]; 
     $result = mysql_query($sql); 
     if(mysql_num_rows($result)){ 
      $data = mysql_fetch_object($result); 

      $nsql = "UPDATE `products` SET `price` = '".$price."', `cover` = 'pics/cover4/".$record[0].".jpg', `cover_big` = 'pics/cover4/".$record[0].".jpg' WHERE `products`.`isbn` = ".$record[0].";"; 
     }else{ 
      $nsql = "INSERT INTO `products` (`id`, `isbn`, `title`, `publisher_id`, `description`, `supplier_id`, `price`, `author`, `cover`, `cover_big`, `status_id`, `timestamp`) 
      VALUES (NULL, '".$record[0]."', '".addslashes($record[1])."', '7','Not Available', '72', '".$price."', '".$record[2]."', 'pics/cover4/".$record[0].".jpg', 'pics/cover4/".$record[0].".jpg', '0',CURRENT_TIMESTAMP);"; 
     } 
     echo $nsql.'<br />'; 
     //echo $price.'<br />'; 
     //echo '<pre>'; print_r($record);exit; 
     } 
     unset($record); 
     $count++; 
    } 
    fclose($file); 
    ?> 

希望能早日聽到有人回來了。

+0

無論出於何種原因,fopen()失敗:文件不存在?無效的權限? –

+0

您可以嘗試指定文件的完整路徑。我的猜測是該文件不存在於您正在運行腳本的同一目錄中,或者腳本無法讀取該文件(權限問題) –

回答

2

呼叫

fopen('NZ_Price_list.csv', 'r'); 

失敗。失敗的調用不會返回所謂的PHP resource,而是一個布爾值。可能的原因是這些:

  • 文件不存在 - file_exists()
  • 應用程序不能打開文件進行讀取 - is_readable()

請更具體的如使用像這樣的絕對路徑,並做一些健全檢查:

$filePath = dirname(__FILE__) . '/..somePath../NZ_Price_list.csv'; 

// Ensure, that file exists and is reable 
if (! file_exists($filePath)) { 
    throw new Exception('File does not exist: ' . $filePath , 10001); 
} 
if (! is_readable($filePath)) { 
   throw new Exception('File not readable: ' . $filePath , 10002); 
} 

// Then, try to open the file 
$fileHandle = fopen($filePath, 'r'); 

if (! is_resource($fileHandle)) { 
    throw new Exception('Failed to open file: ' . $filePath , 10003); 
} 

Furtermore,PHP的stat()通話可能的幫助。 stat()提供了一個文件的詳細信息 - 但也可能失敗...

+0

感謝您的回覆,請您在第一行向我解釋$ filepath 。我不確定它是如何工作的。 – user2636163

+0

@ user2636163 dirname(__FILE__)是當前正在運行的腳本的路徑。我建議創建一個絕對文件路徑。 – SteAp