如何在PHP中读取控制台/用户输入?

时间:2014-05-13 03:02:27

标签: php terminal

我使用gets在Ruby中获取用户输入。

# in 0015.rb
input_num = gets.to_i
p "Your input number is #{input_num}."

我在终端中使用它。

➜  rubytest: ruby 0015.rb
24
"Your input number is 24."    

我可以在PHP中使用终端吗?

3 个答案:

答案 0 :(得分:7)

我认为您正在寻找readline函数

$number = readline("Enter a number: ");
echo 'You picked the number: '.$number;

http://www.php.net/manual/en/function.readline.php

答案 1 :(得分:0)

如果您没有安装readline,或者-您正在编写库,则应执行以下操作:

if (!function_exists('readline')) {
    function readline($question)
    {
        $fh = fopen('php://stdin', 'r');
        echo $question;
        $userInput = trim(fgets($fh));
        fclose($fh);

        return $userInput;
    }
}

$age = readline('What is your age? ');
echo "You are $age years old.\n";

答案 2 :(得分:0)

您可以使用readline功能。但是,如果搜索数组输入,则还必须使用爆炸功能。参见给定示例获取数组输入,

<?php 
    //input 1 6 5
    $a = explode(' ', readline()); //read array
    for($i=0;$i<sizeof($a);$i++)
    {
       echo $a[$i]." ";
    }

?> 
Output:
1 6 5

使用fscanf()函数与C语言中的fscanf()函数相同。我们可以从Keyboard(STDIN)读取2个整数,如下所示:

这与以前的方法不同

<?php 
  
// Input 1 5 
fscanf(STDIN, "%d %d", $a, $b); 
   
// Output 
// The sum of 1 and 5 is 6 
echo "The sum of " . $a . " and "
    . $b . " is " . ($a + $b); 
?> 


Output:
The sum of 1 and 5 is 6

例如Link

相关问题