【问题标题】:How to concatenate variable with Curl code Php [duplicate]如何使用 Curl 代码 Php 连接变量 [重复]
【发布时间】:2019-09-15 23:47:59
【问题描述】:

我想在 curl 代码中连接变量,我该怎么做? 我尝试使用以下代码但不适合我,这是我的代码

$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}}",
);

【问题讨论】:

标签: php json curl


【解决方案1】:

如果您尝试发送 JSON,最好使用 json_encode 编码数组:

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

如果你在 linter 中检查你的 "{\"id\":$id,\"type\":\.$type}}",你会发现这个 json 是无效的。正确的 json 应该是 "{\"id\":$id,\"type\":\"$type\"}",但正如我已经说过的,请改用 json_encode

【讨论】:

  • ,我如何编码以下行? 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\":\"a@codnostic.com\",\"phone\":{\"country_code\":\" 965\"}}"
  • 使用json_encode,阿米特。您似乎不分析答案,而只是盲目地复制粘贴它们:-/从已经发布的内容中学习。
【解决方案2】:

您可以对这些字段进行json_encode,

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

// 并将其作为您尝试构建的 json 编码字符串传递给 postfields

    CURLOPT_POSTFIELDS => $temp

【讨论】:

  • 在这种情况下,密钥将是 01,这与 OP 实际想要的内容相反......
  • 谢谢老兄,我做了修改。
  • 好。现在你的答案完全复制了我的:D
  • 是的别名种类,不同的方式。
  • @RahulMeshram 我如何编码以下行? 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\":\"a@codnostic.com\",\"phone\":{\"country_code\":\" 965\"}}"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 2014-07-20
  • 2014-06-03
  • 2015-07-22
  • 2022-01-02
  • 2012-07-29
相关资源
最近更新 更多