【发布时间】:2021-04-04 11:24:45
【问题描述】:
我打算用这个api做一个链接缩短服务,本站的api地址如下:
http://mitly.ir/api.php
例如对于这个请求:
http://mitly.ir/api.php?url=https://google.com
这会输出 json:
{
"longurl": "https:\/\/google.com",
"shorturl": "http:\/\/mitly.ir\/12MxP",
"stats": "http:\/\/mitly.ir\/stats.php?id=12MxP"
}
现在我写了下面的代码来使用这个api,可惜返回给我的输出是null:
//API Url
$url = 'http://mitly.ir/api.php';
//Initiate cURL.
$ch = curl_init($url);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "url=https://google.com");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
//Execute the request
$result = curl_exec($ch);
//echo $result;
$response = json_decode($result, true);
var_dump($response);
echo "your url is :".$response['result']['shorturl'];
请帮我解决这个问题
【问题讨论】:
-
在
$response['result']中,JSON 中的'result'在哪里? -
请求必须是
GET。删除curl_setopt($ch, CURLOPT_POST, 1); -
@Lessmore 如果我删除该行,结果是相同的'null'
-
同时删除
CURLOPT_POSTFIELDS行并将url=https://google.com附加到结束$url -
@Lessmore 类似这样:` $url = 'mitly.ir/api.php'.'url=https://google.com';`