Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the PHP syntax for File/terminal output formatting?

I want to create a command line program using PHP. How do I design the program's I/O? I can send output as text. I am wondering about the specific output syntax. For example: In HTML i use <br/> to pass to a new line. How can I do this using terminal/file output? Is there a reference for terminal/file oriented programming in PHP?

like image 586
Oguz Bilgic Avatar asked Apr 30 '09 11:04

Oguz Bilgic


People also ask

What is CLI PHP?

PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.

Can we use PHP to write command line script?

Yes, we can create a command-line PHP script as we do for web script, but with few little tweaks. We won't be using any kind of HTML tags in command-line scripting, as the output is not going to be rendered in a web browser, but displayed in the DOS prompt / Shell prompt.


2 Answers

Writing command-line PHP scripts is quite simple, actually. You output text in the exact same way you would normally: print and echo both print text to the console. The only difference here is that you can't use HTML tags for formatting, since your code isn't being interpreted by a web browser (i.e. "\n" will actually create a visible line break, not <br />).

Reading input from stdin is a little trickier, but all it really involves is essentially using some of the file reading functions (e.g. fgets(), fgetc(), fscanf()) and passing in STDIN as the file path (or php://stdin, depending on how new your version of PHP is).

And yes, there is a reference for command-line programming in PHP on php.net. It covers pretty much everything you need to know to work with PHP in a command-line environment.

like image 173
hbw Avatar answered Sep 22 '22 04:09

hbw


When writing a CLI script consider ending lines with PHP_EOL so it will be cross platform compatible with UNIX ( \n ), Windows ( \n\r ) and Mac ( \r ). And when you whant to print it as html use the PHP's nl2br function.

like image 43
Radu Maris Avatar answered Sep 22 '22 04:09

Radu Maris