如何编写命令行交互式PHP脚本? [英] How do I write a command-line interactive PHP script?

查看:279
本文介绍了如何编写命令行交互式PHP脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个可从命令行使用的PHP脚本.我希望它提示并接受一些项目的输入,然后吐出一些结果.我想在PHP中执行此操作,因为我所有的类和库都在PHP中,并且我只想为一些事情建立一个简单的命令行界面.

I want to write a PHP script that I can use from the command line. I want it to prompt and accept input for a few items, and then spit out some results. I want to do this in PHP, because all my classes and libraries are in PHP, and I just want to make a simple command line interface to a few things.

提示和接受重复的命令行输入是使我绊倒的部分.我该怎么做?

The prompting and accepting repeated command line inputs is the part that's tripping me up. How do I do this?

推荐答案

来自

您需要一个特殊文件: php://stdin ,它代表标准输入.

You need a special file: php://stdin which stands for the standard input.

print "Type your message. Type '.' on a line by itself when you're done.\n";

$fp = fopen('php://stdin', 'r');
$last_line = false;
$message = '';
while (!$last_line) {
    $next_line = fgets($fp, 1024); // read the special file to get the user input from keyboard
    if (".\n" == $next_line) {
      $last_line = true;
    } else {
      $message .= $next_line;
    }
}

这篇关于如何编写命令行交互式PHP脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆