我正在使用 namechk.com API来检查社交媒体名称是否可用(Twitter)。当我在终端中发出 cURL 请求时,它工作正常,但在 PHP 中运行时出现错误。
终端中的以下查询工作正常:
curl -i -H "AUTHORIZATION: Bearer xxxxxxxxxx" -H "Accept: application/vnd.api.v1+json" -d "site=twitter&username=namechk" "https://api.namechk.com/services/check.json"
按照 namechk.com 的文档,以下内容应该可以工作(未经修改,直接取自文档):
<?php
$http_options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode(array('site' => 'twitter', 'username' => 'namechk')),
'header' => array("AUTHORIZATION: Bearer xxxxxxx".PHP_EOL, "Accept: application/vnd.api.v1+json".PHP_EOL, "Content-Type: application/json".PHP_EOL)
));
$context = stream_context_create($http_options);
$contents = file_get_contents("https://api.namechk.com/services/check.json", false, $context);
$results = json_decode($contents, true);
。除了我收到错误:
Warning: file_get_contents(https://api.namechk.com/services/check.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
我使用 cURL 为 PHP 编写了一个返回空的函数:
public function checkSite($username, $service) {
$ch = curl_init('https://api.namechk.com/services/check.json');
$headers = array(
"AUTHORIZATION: Bearer {$this->token}",
"Accept: application/vnd.api.v1+json",
"Content-Type: application/json"
);
curl_setopt_array($ch , array(
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => array(
'site' => $service,
'username' => $username
),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true
));
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
固定。
问题是在标头数组中,API 文档PHP_EOL
附加到每个元素。删除它,它可以工作。