dongsou3041 2014-12-16 15:40
浏览 99
已采纳

通过终端将PHP生成的CSV文件上传到SFTP服务器

I have a PHP file which generates a CSV file using the code below:

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;

I've not included the code which creates the content as it does it's job fine. What I need to do is use terminal to run this file and upload the results to an sftp server. I can connect to the server fine in terminal.

I have been using the php command in terminal to produce the resulting CSV. This however doesn't produce the CSV like it does when run in the browser. What it does do is produce the CSV as a string.

Is there a way to either produce the CSV as a file like the browser so I can grab it in terminal and upload it to the SFTP server? Alternatively is it possible to echo out the string produced from the PHP file and create the CSV myself using this kind of command:

echo "boo,to,you">file.csv
  • 写回答

1条回答 默认 最新

  • donglin6659 2014-12-17 08:41
    关注

    Just redirect the php output to a temporary file and upload the file.

    php yourscript.php > /tmp/file.csv
    echo "put /tmp/file.csv" | sftp user@example.com
    

    If you want to do it without the temporary file, you cannot do with just the (OpenSSH) sftp as it cannot read contents to upload from the stdin. Neither the (OpenSSH) scp can.


    You can of course produce the file from PHP code itself, if that suits your task better.

    Just use the file_put_contents():

    file_put_contents("/tmp/file.csv", $csv_output);
    

    See How to write into a file in PHP?


    The suggestion by @MarcB should work, if the remote server is *nix (understands the cat) and allows a shell access.

    php yourscript.php | ssh user@example.com 'cat > file.csv'
    

    Though obviously that's not "SFTP upload" anymore.


    When producing a file, do not use the the header(). Headers make sense in webserver environment only, not when you use the PHP as a scripting language in a shell.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号