-3

I want to cocatenate variable in curl code,How can i do this ? I tried with following code but not working for me,Here is my code

$id = $_POST['id'];
$type = $_POST['type'];    

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://xxxxxxxxxxx.com",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_POSTFIELDS => "{\"id\":$id,\"type\":\.$type}}",
);
2
  • you have a syntax error. Commented Apr 26, 2019 at 12:51
  • That would be "interpolation", not concatenation. Though json_encodeing the real structure would be better. Commented Apr 26, 2019 at 12:52

2 Answers 2

3

You can json_encode these fields,

$temp = json_encode(['id' => $id, 'type' => $type]);

// and pass it to postfields as json encoded string which you are trying to build

    CURLOPT_POSTFIELDS => $temp
Sign up to request clarification or add additional context in comments.

5 Comments

the keys will be 0 and 1 in that case, which negates with what OP actually wants...
Thanks mate, I made changes.
Good. And now your answer precisely copies mine :D
Yeah alias kind, different way.
@RahulMeshram How can i encode following line ? CURLOPT_POSTFIELDS => "{\"amount\":2,\"currency\":\"KWD\",\"employerid\":\"123\",\"threeDSecure\":true,\"save_card\":false,\"description\":\"Test Description\",\"statement_descriptor\":\"Sample\",\"metadata\":{\"employerid\":$id,\"type\":\"test 2\"},\"reference\":{\"transaction\":\"txn_0001\",\"order\":\"ord_0001\"},\"receipt\":{\"email\":true,\"sms\":true},\"customer\":{\"first_name\":\"test\",\"middle_name\":\"test\",\"last_name\":\"test\",\"full_name\":\"test\",\"email\":\"[email protected]\",\"phone\":{\"country_code\":\"965\"}}"
2

If you're trying to send JSON, you're better off with encoding an array with json_encode:

CURLOPT_POSTFIELDS => json_encode(["id" => $id, "type" => $type])

If you check your "{\"id\":$id,\"type\":\.$type}}" in a linter, you will see that this json is invalid. The correct json would be "{\"id\":$id,\"type\":\"$type\"}", but as I already said, use json_encode instead.

2 Comments

,How can i encode following line ? CURLOPT_POSTFIELDS => "{\"amount\":2,\"currency\":\"KWD\",\"employerid\":\"123\",\"threeDSecure\":true,\"save_card\":false,\"description\":\"Test Description\",\"statement_descriptor\":\"Sample\",\"metadata\":{\"employerid\":$id,\"type\":\"test 2\"},\"reference\":{\"transaction\":\"txn_0001\",\"order\":\"ord_0001\"},\"receipt\":{\"email\":true,\"sms\":true},\"customer\":{\"first_name\":\"test\",\"middle_name\":\"test\",\"last_name\":\"test\",\"full_name\":\"test\",\"email\":\"[email protected]\",\"phone\":{\"country_code\":\"965\"}}"
use json_encode, Amit. You seem like you do not analyse the answers, but only copy-paste them blindly :-/ Learn from what has already been posted.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.