mrytrohs
mrytrohs

Reputation: 43

CURLOPT_POSTFIELDS format

I am trying to pass a json string into a curlopt_postfield.

curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);

I have a working hard coded example. However I am having trouble making it dynamic.

$test = "84560";
$data = "{\"id\":\"" .$test. "\"}";
$data2 = "{\"id\":\"84560\"}";
curl_setopt($ch, CURLOPT_POSTFIELDS, $data2);

Why does $data2 work and $data fail? I have tried json encoding, utf8 encoding, and lots of variations of escaping the quotes all to no avail. What am I missing? I do not get an error simply a NULL response.

Here is the full code. Still not able to get it working. Any additional suggestions as I have tried everything I have found.

$test = "84560";
$data = "{\"id\":\"" .$test. "\"}";
$data2 = "{\"id\":\"84560\"}";

$result2 = getJson("results.json?", $data2);

function getJson($endpoint, $postfields) 
{
    $URL = "https://app.mobilecause.com/api/v2/reports/". $endpoint;

        $ch = curl_init();
        $headers = [];
        $headers[] = "Authorization: Token token=\"[token goes here]\"";
        $headers[] = "Accept: application/json";
        $headers[] = "Content-Type: application/json";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        curl_setopt($ch, CURLOPT_URL, $URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $result = curl_exec($ch);
        if (curl_errno($ch)) 
        {
            echo 'Error:' . curl_error($ch);
        }
        curl_close ($ch);;
        return $result;
    }

Upvotes: 1

Views: 2477

Answers (1)

Riad Loukili
Riad Loukili

Reputation: 119

You should simply try:

<?php
$data = array('id' => 84560);
$json = json_encode($data);
echo $json; // Will print { id: 84560 }

Upvotes: 2

Related Questions