2013-08-27 121 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