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!

4
  • 2
    Does this answer your question? What is the difference between single-quoted and double-quoted strings in PHP? Commented Jan 25, 2022 at 8:43
  • You have to use doublequotes " instead of single quotes ' if you want variables to be injected in the string. Commented Jan 25, 2022 at 8:43
  • $methodParams = '{ "date_confirmed_from": ' . $date. ', "get_unconfirmed_orders": false }'; Commented Jan 25, 2022 at 8:46
  • 4
    Don't manually create your json like that. Just create a PHP array with the correct structure and use json_encode() to turn it into json. Commented Jan 25, 2022 at 8:51

2 Answers 2

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
}';
Sign up to request clarification or add additional context in comments.

1 Comment

The json_encode()-path is the way to go.
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
            }';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.