5

Using PHP 5.3 if I send a JSON encoded string as an arugment via command line...

/usr/local/bin/php -q /path/to/script.php {"key":"test","cache":1}

... and in script.php the code is:

<?php print_r($argv); ?>

I get back:

Array
(
    [0] => /path/to/script.php
    [1] => key:test
    [2] => cache:1
)

Which is completely unexpected!

Whilst I can live with this I'd like to know where this is documented by PHP so that I am 100% sure it will work like this if I pass a JSON encoded string as an argument every time.

Also arrays within the JSON string don't seem to work as expected.

1
  • Did you figure out how to parse Json from the command line parameter in PHP scripts? Commented May 23, 2013 at 17:44

1 Answer 1

5

If want to use special characters in a cli argument, you should always encapse them in quotes

"{\"key\":\"test\",\"cache\":1}"

'{"key":"test","cache":1}'
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I figured that, but it's interesting that PHP attempted to parse the string yet this feature doesn't seem to be well known.
As you can read in your output its not parsed. On the command line you can define multiple arguments at once via list notation {a,b,c} (for example in mkdir -p path/to/{folderA,folderB}). The JSON-object looks similar and is therefore misinterpreted. As far as I know its not PHPs fault, but just the way CLI-calls "work".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.