Categories
Uncategorized

How to pass a JSON string in Command line with PHP

If you try to pass a JSON string as a command line argument in the Terminal like this:

Plain Text

It is expected to that $argv[1] will contain the JSON string. But unfortunately, it gets chunked. This is what you get when you do a print_r :

Plain Text
process.php

This is not desired. We want the whole JSON string in one index, but the terminal breaks it into multiple chunks. To fix this problem we need to use proper escaping. This is what we do:

  1. Wrap the JSON in double quotes (“”)
  2. Add escape character (\) before double quotes present inside the JSON. You can do this with addslashes()

The JSON will now look like this

Plain Text

This should work as expected:

Plain Text

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.