问题描述
我想从PHP命令行界面传递参数,然后使用PHP脚本读取值,如下所示:
I want to pass parameters from PHP Command Line Interface, and then read in the values using PHP script, something like this:
<?php
$name1 = $argv[1];
echo $name1;
?>
我这样从CLI传递变量:
I pass the variable from CLI like this:
C:\xampp\php\php.exe name.php Robby
上面的作品,我得到罗比作为输出.
The above works, I get Robby as the output.
但是我想做这样的事情:
But I want to do something like this:
C:\xampp\php\php.exe name.php -inputFirstName="Robby"
这样,用户就会被告知在正确的位置输入正确的参数.解析这些参数的合适方法是什么?
So that the user is well informed to enter the correct parameters in the correct places. What is the appropriate way to parse these parameters?
推荐答案
从命令行调用PHP脚本时,可以使用$ argc找出要传递的参数数量,并可以使用$ argv来访问它们.例如,运行以下脚本:
When calling a PHP script from the command line you can use $argc to find out how many parameters are passed and $argv to access them. For example running the following script:
<?php
var_dump($argc); //number of arguments passed
var_dump($argv); //the arguments passed
?>
像这样:-
php script.php arg1 arg2 arg3
将给出以下输出
int(4)
array(4) {
[0]=>
string(21) "d:\Scripts\script.php"
[1]=>
string(4) "arg1"
[2]=>
string(4) "arg2"
[3]=>
string(4) "arg3"
}
See $argv and $argc for further details.
要做你想做的事
php script.php arg1=4
您需要将等号上的参数展开:-
You would need to explode the argument on the equals sign:-
list($key, $val) = explode('=', $argv[1]);
var_dump(array($key=>$val));
这样,您可以在等号前面拥有所需的任何内容而不必解析它,只需检查key => value对是否正确即可.但是,这只是浪费,只是指导用户按照正确的顺序传递参数.
That way you can have whatever you want in front of the equals sign without having to parse it, just check the key=>value pairs are correct. However, that is all a bit of a waste, just instruct the user on the correct order to pass the arguments.
这篇关于PHP,将参数从命令行传递到PHP脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!