Monday, August 31, 2009

php command line arguments

One of the cool things about PHP is the abundance of ready made built-in functions.

I write a lot of PHP shell scripts.

PHP, like almost any other proper language, accepts arguments in a $argv array, where the 1st argument ($argv[0]) is the filename, and then all of the rest of the arguments.

But what happens if you don't always want to accept the parameters as a command-line argument?

Then you either have to pass a predefined 'placeholder' that nominates 'use default value', or you have to define flags, and build a parsing mechanism to cut off the first character or two, and then define what to do with the rest.

This is where getopt() comes in handy.

All you have to do is define a. the different options the script can accept. b. if the option is required and/or accompanied with an additional argument.

example:

$options = getopt("ab:c:C::");

a is a standalone - no additional argument required (obviously - not required).
b: is required.
so is c: .
C:: (Capital C) is optional. (PHP 5.3 and up).

$options is an (associative) array of all passed parameters (with arguments, if applies).

Now that's effective.

Thursday, August 6, 2009

neatly print out PHP arrays

Use this function to neatly print out your arrays;

function print_r_html($data,$return_data=false) {

$data = print_r($data,true);

$data = str_replace( " "," ", $data);

$data = str_replace( "\r\n","
\r\n"
, $data);

$data = str_replace( "\r","
\r"
, $data);

$data = str_replace( "\n","
\n"
, $data);


if (!$return_data)

echo $data;

else

return $data;

}


displaying php source file


Ever wonder how to take a PHP file, and display it color coded in a web browser?

Well... Wonder no more!

PHP CLI (Command Line Interpreter) comes with this nifty feature that does this automatically for you.

php -s filename.php > filename.html

creates a html output of the php file.

Cool, ain't it?