【发布时间】:2016-05-13 05:27:57
【问题描述】:
我正在尝试在 PHP 中执行一个使用 JSON 数组的 curl 语句。我将在下面发布我的代码,并稍微解释一下我想要做什么
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 = '[{"phoneNumber":"15551231234","message":"Click here http://link.it/i.htm?id=55&key=23987gf2389fg"}]';
一切看起来都不错。如果 $msg 变量中没有链接,则由 params 创建的 JSON 数组实际上可以完美运行。我能够成功执行 CURL 调用。唯一失败的时候是我将链接添加到我的 $msg 变量。
我已经联系了 API 的支持团队,他们告诉我一切都应该正常工作。
此时我猜测链接需要以某种方式转义,然后才能写入 JSON 数组。我试过用反斜杠转义冒号和正斜杠,但它不能解决问题。有没有人可以阐明如何传递网址?
提前谢谢你!!
【问题讨论】:
-
不要手工制作 JSON。使用 PHP
json_encode()函数。它负责创建正确的 JSON。
标签: javascript php json curl callfire