0

I have this function:

function api()
{
    $date = time()- 86400;
    
    $method = "getOrders";
    
            $methodParams = '{
                "date_confirmed_from": $date,
                "get_unconfirmed_orders": false
            }';
            $apiParams = [
                "method" => $method,
                "parameters" => $methodParams
            ];
            
            $curl = curl_init("https://api.domain.com");
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_HTTPHEADER, ["X-BLToken:xxx"]);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($apiParams));
            $response = curl_exec($curl);
        
            return $response;
}

I want to put on line 8 variable date and I have tried {$date} $date '.$date.' ".$date." every time I get error from api

If I put value manually like 1589972726 it working, but I need to get value from $date variable!

Thank you!

  • 2
    Does this answer your question? [What is the difference between single-quoted and double-quoted strings in PHP?](https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php) – Ivar Jan 25 '22 at 08:43
  • You have to use doublequotes `"` instead of single quotes `'` if you want variables to be injected in the string. – Patrick Janser Jan 25 '22 at 08:43
  • $methodParams = '{ "date_confirmed_from": ' . $date. ', "get_unconfirmed_orders": false }'; – Rao DYC Jan 25 '22 at 08:46
  • 4
    Don't manually create your json like that. Just create a PHP array with the correct structure and use [json_encode()](https://www.php.net/manual/en/function.json-encode.php) to turn it into json. – M. Eriksson Jan 25 '22 at 08:51

2 Answers2

2

Maybe it is less confusing, if you use an array and convert it to the needed format later:

$methodParams = [
   "date_confirmed_from" => $date,
   "get_unconfirmed_orders" => false
];
$apiParams = [
   "method" => $method,
   "parameters" => json_encode($methodParams)
];

Have a look at the documentation of json_encodefor details:

https://www.php.net/manual/function.json-encode.php

Anyways, using the same quotes that started the string to close it, should work too:

$methodParams = '{
    "date_confirmed_from": ' . $date . ',
    "get_unconfirmed_orders": false
}';
t.h3ads
  • 1,858
  • 9
  • 17
0

Because you have single quote on that string, you need to inject with single quote: '.$date.',

if you would have double quote you use {$date} or \"$date\"

$methodParams = '{
                "date_confirmed_from": '.$date.',
                "get_unconfirmed_orders": false
            }';
BoBiTza
  • 98
  • 13