将 URL 传递到 JSON 数组

Passing a URL into a JSON array

我正在尝试在 PHP 中执行一个使用 JSON 数组的 curl 语句。我将 post 我的代码在下面对我试图做的事情做一些解释

function doPost($url, $user, $password, $params) {
  $authentication = 'Authorization: Basic '.base64_encode("$user:$password");
  $http = curl_init($url);
  curl_setopt($http, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($http, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($http, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($http, CURLOPT_URL, $url);
  curl_setopt($http, CURLOPT_POST, true);
  curl_setopt($http, CURLOPT_POSTFIELDS, $params);
  curl_setopt($http, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json', $authentication));
  return curl_exec($http);
}

$link = "http://link.it/i.htm?id=55&key=23987gf2389fg";
$phone = '5551231234';
$phone = '1' . $phone;

//Write message
$msg = "Click here " . $link;
$params = '[{"phoneNumber":"'.$phone.'","message":"'.$msg.'"}]';

//Send message
$return = doPost('https://api.link.com','username','password',$params);
echo $return;

Params 最终成为

$params = '[{"phoneNumber":"15551231234","message":"Click here http://link.it/i.htm?id=55&key=23987gf2389fg"}]';

一切看起来都不错。如果 $msg 变量中没有 link,则由 params 创建的 JSON 数组实际上可以完美运行。我能够执行成功的 CURL 调用。唯一一次失败是当我将 link 添加到我的 $msg 变量时。

我已经联系了 API 的支持团队,他们告诉我一切都应该在他们这边进行。

此时我猜测 link 需要以某种方式转义才能写入 JSON 数组。我试过用反斜杠转义冒号和正斜杠,但它不能解决问题。有没有人可以阐明如何通过 url?

提前致谢!!

不要手动构建 JSON。构造和数组或 object 然后在其上调用 json_encode()。

$params = array();
$object = array("phone"=>$phone, "message"=>$linkMsg);
$params[] = (object) $object;

$param_json_string = json_encode($params);

然后在使用curl通过POST提交JSON时,需要在header.

中指定字符串的长度
curl_setopt($http, CURLOPT_HTTPHEADER, 
            array( 'Content-Type: application/json', 
                   'Content-Length: '. strlen($param_json_string)));           

当然,这是对其他 header 的补充,例如您正在设置的身份验证(正如我看到您在 doPost() 方法中所做的那样)。