If you try to pass a JSON string as a command line argument in the Terminal like this:
Plain Text
1
php process.php {user_id: 1, name: "Pramod"}
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
xxxxxxxxxx
8
1
Array
2
(
3
[0] => test.php
4
[1] => {user_id:
5
[2] => 1,
6
[3] => name:
7
[4] => Pramod}
8
)
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:
- Wrap the JSON in double quotes (“”)
- 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
xxxxxxxxxx
1
1
php process.php "{user_id: 1, name: \"Pramod\"}"
This should work as expected:
Plain Text
xxxxxxxxxx
5
1
Array
2
(
3
[0] => test.php
4
[1] => {user_id: 1, name: "Pramod"}
5
)