【问题标题】:Link Shortener Service API Return Null [duplicate]链接缩短服务 API 返回 Null [重复]
【发布时间】: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';`

标签: php json api curl


【解决方案1】:

从您的示例中,您需要 GET 请求:

$short = 'https://google.com';
$url = 'http://mitly.ir/api.php?url='.$short;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    $result = curl_exec($ch);
    $response = json_decode($result, true);
    var_dump($response);

【讨论】:

  • 仍然返回 null
  • 您需要将其与对副本的处理结合起来(即答案here
  • 函数 remove_utf8_bom($text) { $bom = pack('H*','EFBBBF'); $text = preg_replace("/^$bom/", '', $text);返回$文本; } 见:stackoverflow.com/questions/10290849/… $response = json_decode(remove_utf8_bom($result), true);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 1970-01-01
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多