读取CSV文件时出错

时间:2013-08-27 22:07:08

标签: php mysql csv

我是非常新的PHP。有人可以解决我的问题吗?

当我尝试在Windows中使用xampp执行时,以下代码非常正常。但是当我尝试通过ssh终端执行时,它在Ubuntu上不起作用。

以下是php警告。但是当我在Windows上尝试它时,它适用于CSV中的所有记录(它为CSV中的每条记录提供了插入或更新语句)

  

PHP警告:feof()要求参数1为资源,布线在第8行的/home/myetexts/Documents/codes/Pearson/test2.php中给出   PHP警告:fgetcsv()期望参数1为资源,第9行/home/myetexts/Documents/codes/Pearson/test2.php中给出布尔值

<?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);
    ?>

希望尽快收到一些人的回复。

1 个答案:

答案 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 );
}

更进一步,PHP的stat()调用可能有所帮助。 stat()提供了文件的详细信息 - 但也可能失败...

相关问题