Reputation: 758
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).
Upvotes: 0
Views: 2909
Reputation: 7602
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.
Upvotes: 3