首页 > 解决方案 > 卷曲请求到 PHP 卷曲请求

问题描述

我需要帮助将此请求重写为 php curl:

curl -d '{"text":"Hello,
#param#.","port":[2,3],"param":[{"number":"123456","text_param
":["John"],"user_id":1},{"number":"123478",
"text_param":["Sam"],"user_id":2}]}’ –H "Content-Type:
application/json" http://gateway_ip/api/send_sms

到目前为止,我没有任何成功。这是我尝试过的:

$url = "http://url/api/send_sms";

$params = array(
    'auth' => 'user:pass',
    'port' => 7,
    'text' => utf8_encode('Hello, world!')
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "user:pass");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);

我做错了什么?

标签: phpapicurl

解决方案


像这样的东西:

<?php
$ch = curl_init();

$json = <<<JSON
{"text":"Hello,
#param#.","port":[2,3],"param":[{"number":"123456","text_param
":["John"],"user_id":1},{"number":"123478",
"text_param":["Sam"],"user_id":2}]}
JSON;

curl_setopt($ch, CURLOPT_URL, "http://gateway_ip/api/send_sms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_POST, 1);

$headers = array();
$headers[] = "Content-Type: application/json";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

自己构建 $json var,但使用json_encode函数创建一个有效的 json


推荐阅读