I was currently trying to test a Zend controller (PHP framework) using curl command to simulate and HTTP POST request. Curl command makes it super simple to build and execute your query and it is highly configurable.

I needed to pass a complex JSON formatted object to my controller but it wasn’t able to understand the parameter. Instead of this approach I decided to build a url-encoded string out of my JSON object and pass that to my controller.

The following code takes a JSON object and at the end echos out a url-encoded string, so that I could easily include it in my curl call.

<?php
$json = '{
  "key1": "value1",
  "key2": "value2",
  "key3": {
    "key4": "value4"
  }
}';

$assoc_arrray = json_decode($json);
$urlEncodedString = http_build_query($assoc_array);

echo $urlEncodedString;

Here is a sample curl call to make a HTTP POST request with url-encoded params:

curl -d 'OUTPUT_OF_YOUR_SCRIPT' myurl.com/controller/method

Resources