dounao2829 2015-03-16 21:32
浏览 20
已采纳

将参数(filename)传递给CLI PHP脚本

I am wanting to write a script in PHP to process text files. I know of a few ways to accomplish this, except the one way I would like to do this. I want to be able to pass a file name, like a traditional command-line application.

For example:

php script.php textfile.txt or script.php textfile.txt

I assume it can be done, because you pass arguments to composer. I just can't find how to do it in the docs or Google.

Can someone point me in the right direction? Or point me to a language that supports this(maybe Python or Groovy, if PHP is not an option).

  • 写回答

1条回答 默认 最新

  • duansen6750 2015-03-16 21:54
    关注

    In php if you run it from the command line you can treat any value after the php as an argument. The inside your script.php you will have access to these arguments in the $argv array.

    for the following would be your php script:

    <?php
    // script.php
    print_r($argv);
    

    Then if you execute that file from the command line:

    > php script.php foo bar testfile.txt

    you will get the following result

    Array
    (
        [0] => script.php
        [1] => foo
        [2] => bar
        [3] => testfile.txt
    )
    

    See the php documentation for more information.

    This is a very simple way to create a script, but if you want to create advanced command line tool programs I recommend using the Symfony2 Console Component.

    The console component will enable you to encapsulate the functionality of each command inside it's own class. Then you can create a simple "console" file that will be able to execute any of these commands. Take a look at a simple example application here.

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

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)