Php 处理argc和argv
我编写的代码如下:Php 处理argc和argv,php,Php,我编写的代码如下: <?php array_shift($argv); $taskid=$argv[0]; $file1=file_get_contents($argv[1]); $file2=fopen($argv[2],"w"); echo $taskid."\n".$file1."\n".$file2."\n"; ?> 我以php myfile.php 1 1.txt 2.txt 其中1是taskid,1.txt是输入文件,2.txt是输出文件。 我想修改这个程序,使它能
<?php
array_shift($argv);
$taskid=$argv[0];
$file1=file_get_contents($argv[1]);
$file2=fopen($argv[2],"w");
echo $taskid."\n".$file1."\n".$file2."\n";
?>
我以php myfile.php 1 1.txt 2.txt
其中1是taskid,1.txt是输入文件,2.txt是输出文件。
我想修改这个程序,使它能够运行,即使我没有传递任何类似php myfile.php
应该运行的参数。我想为它设置一个if条件。我曾使用过类似于if(*argv的条件,请尝试以下方法:
<?php
array_shift($argv);
if (empty($argv) || count($argv) != 3) {
echo "Incorrect number of arguments\n";
}
else {
$taskid = $argv[0];
$file1 = file_get_contents($argv[1]);
$file2 = fopen($argv[2],"w");
echo $taskid . "\n" . $file1 . "\n" . $file2 . "\n";
}
是的,但是我要补充一点,因为这个问题是关于没有参数的,所以在这种情况下我会投票支持if($argc==1)
<?php
array_shift($argv);
if (empty($argv) || count($argv) != 3) {
echo "Incorrect number of arguments\n";
}
else {
$taskid = $argv[0];
$file1 = file_get_contents($argv[1]);
$file2 = fopen($argv[2],"w");
echo $taskid . "\n" . $file1 . "\n" . $file2 . "\n";
}