dongzhang6021 2016-08-05 08:11
浏览 84

如何在laravel artisan控制台中将文件作为输入?

I am working with a laravel application and I instead of inputting just arguments and options, I want to know if there is a way where I can input files. I wish to import a lot of data from other APIs and I am using Guzzle to do that.

A lot of the times the same data is being imported at each database reset. Which is why I imported the data in a json file collection first and then I use that collection every time to insert the data in the database which saves the time to fetch the data each time from the other API.

Right now I am hard coding the file which is used but is there a way where I can fetch the file via the command line where I specify the arguments and options for the console command?

  • 写回答

1条回答 默认 最新

  • dongrou839975 2016-08-05 09:39
    关注

    There are many ways you could do that.

    One option would be to pass file path as command argument and then read the file using basic file_get_contents() function.

    class YourCommand extends Command {
      public function fire() {
        dd(file_get_contents($this->argument('path'));
      }
    
      protected function getArguments()
      {
          return [['path', InputArgument::REQUIRED, "File path"]];
      }
    }
    

    You could also make use of Laravel's Filesystem Library and setup a local storage (see https://laravel.com/docs/5.1/filesystem for more details) and put the file in your storage/app folder:

    class YourCommand extends Command {
      public function fire() {
        dd(Storage::get($this->argument('path')));
      }
    
      protected function getArguments()
      {
          return [['path', InputArgument::REQUIRED, "File path"]];
      }
    }
    

    If you want to avoid providing file path, the simplest way would be to just read the file from STDIN stream by retrieving the contents from the I/O stream:

    class YourCommand extends Command {
      public function fire() {
        dd(file_get_contents('php://stdin'));
      }
    }
    

    You'd just need to run the command like the following:

    php artisan yourcommand < file.json
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题