Brentnauer Brentnauer - 18 days ago 6x
JSON Question

Using CURL to post JSON with PHP variables

I'm trying to set up account creation via a payment form on my website using ZenDesk's API. The example code they give is:

curl -v -u {email_address}:{password} https://{subdomain} \
-H "Content-Type: application/json" -X POST -d '{"user": {"name": "Roger Wilco", "email": ""}}'

Since I need to include PHP variables, I'm trying to use this:

$data = array("name" => $entry["1"], "email" => $entry["3"], "role" => "end-user");
$data_string = json_encode($data);

$ch = curl_init('');
curl_setopt($ch, CURLOPT_USERPWD, "");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))

$result = curl_exec($ch);

However, it's not working. Is my code correct in terms of duplicating the function of the first snippet?


I found another example of ZenDesk's API and was able to come up with this:

define("ZDUSER", "");
define("ZDURL", "");

/* Note: do not put a trailing slash at the end of v2 */

function curlWrap($url, $json, $action)
  $ch = curl_init();
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
    curl_setopt($ch, CURLOPT_URL, ZDURL.$url);
    curl_setopt($ch, CURLOPT_USERPWD, ZDUSER."/token:".ZDAPIKEY);
            case "POST":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
        case "GET":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        case "PUT":
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $output = curl_exec($ch);
    $decoded = json_decode($output);
    return $decoded;

$arr = array("z_name"=>$namevariable,
$create = json_encode(array('user' => array('name' => $arr['z_name'], 'email' =>     $arr['z_email'], 'role' => $arr['z_role'])), JSON_FORCE_OBJECT);
$data = curlWrap("/users.json", $create, "POST");

It appears to be working on its own, so this answers the question as it exists here.

Thanks for your help everyone :)