【问题标题】:fopen with cron jobfopen 与 cron 作业
【发布时间】:2013-01-17 08:15:13
【问题描述】:

谁能告诉我我做错了什么?我有一个 php 脚本,它应该使用 cron 作业执行,从数据库中提取数据并将其放入 csv 文件中。 当我从浏览器运行它时,它工作得很好,所以我确定我的查询是正确的。但是,当我使用 cron 作业时,它返回“No input file specified.”并且不写入文件。

这是我的代码:

CRON:

/home/ACCOUNT_NAME/public_html/directory/report.sh

report.sh

php -q /home/ACCOUNT_NAME/public_html/directory/report.php
php -q /home/ACCOUNT_NAME/public_html/directory/report_mail.php

report.php

<?php

    $con = mysql_connect("localhost", "my_un", "my_pw") ;

    if(!$con){
        die('Could not connect: ' . mysql_error()) ;
        }
    mysql_select_db("my_db", $con) ;

if (!function_exists('fputcsv')){
        function fputcsv($objFile,$arrData,$strDelimiter=',',$strEnclose='"') {
            $strNewLine="\n";
            $strToWrite = '';
            foreach ($arrData as $strCell){
                //Test if numeric
                if (!is_numeric($strCell)){
                    //Escape the enclose
                    $strCell = str_replace($strEnclose,$strEnclose.$strEnclose,$strCell);
                    //Not numeric enclose
                    $strCell = $strEnclose . $strCell . $strEnclose;
                }
                if ($strToWrite==''){
                    $strToWrite = $strCell;
                } else {
                    $strToWrite.=  $strDelimiter . $strCell;
                }
            }
            $strToWrite.=$strNewLine;
            fwrite($objFile,$strToWrite);
        }
}

// CUT - MY QUERY HERE


$fp = fopen("/reports/report.csv" , "w+");

foreach ($list as $line) {
    fputcsv($fp, split(',', $line));
}
?>

csv文件应该存放在

/home/ACCOUNT_NAME/public_html/directory/reports/report.csv

我在这里缺少什么? TIA

【问题讨论】:

标签: php cron


【解决方案1】:

您没有保存到正确的目录。而是这样做

$fp = fopen(__DIR__ . "/reports/report.csv" , "w+");

【讨论】:

    【解决方案2】:

    问题在于,当您以 / 开始您的 fopen() 参数时,您将转到服务器根目录,而不是 Web 根目录。因此,您要么需要提供文件的完整路径fopen(),要么像这样动态检索当前目录:

    $this_directory = dirname( __FILE__ );
    $fp = fopen($this_directory . "/reports/report.csv" , "w+");
    

    【讨论】:

      【解决方案3】:
      $fp = fopen("/reports/report.csv" , "w+");
      

      这不会写入您希望文件去往的位置。它将尝试在文件系统根目录的reports 目录中创建它。

      【讨论】:

        【解决方案4】:

        这个答案可能离题,但 MySQL 能够使用“INTO OUTFILE”将查询结果直接输出到 CSV 文件。

        注意 MySQL 应该与所需的输出文件位置在同一台服务器上运行

        请参见此处的示例: MySQL export into outfile : CSV escaping chars

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-03-09
          • 2018-07-31
          • 1970-01-01
          • 2012-09-04
          • 2016-07-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多