Php 使用cURL从API获取JSON不会返回任何结果

Php 使用cURL从API获取JSON不会返回任何结果,php,json,curl,Php,Json,Curl,我已经开始制作一个网页,它使用另一个网站的API来获取用于验证网站的电话号码,我已经开始使用Python了。但是,当我尝试使用cURL从API获取JSON数据时,它不会返回任何结果。下面是PHP的代码 echo "Requesting number..."; $url = 'api.php'; # changed from the actual website $params = array( 'metod' => 'get_number', # misspelt because

我已经开始制作一个网页,它使用另一个网站的API来获取用于验证网站的电话号码,我已经开始使用Python了。但是,当我尝试使用cURL从API获取JSON数据时,它不会返回任何结果。下面是PHP的代码

echo "Requesting number...";
$url = 'api.php'; # changed from the actual website

$params = array(
    'metod' => 'get_number', # misspelt because it is not an english website
    'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
    'country' => 'RU',
    'service' => 'XXXXX',
 );

$ch = curl_unit();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);

$result = curl_exec($ch);
if(curl_errno($ch) !== 0) {
    error_log('cURL error when connecting to ' . $url . ': ' . curl_error($ch));
}

curl_close($ch);

print_r($result);`

我希望,当代码在服务器上执行时,它应该提供文件中的所有JSON,然后我可以稍后使用这些JSON来挑选它的某些部分,以便在其他地方使用。但是,实际结果是,它不会打印任何内容,如图所示:

我不知道为什么您的代码不起作用,但更简单的替代方法是使用:


嗨,艾丹,你可以试试API调试。只需将程序安装到您的pc上,您就可以尝试任何类型的API请求first@JohnnyB1988问题不在于API,而是我不知道如何在PHP中获取JSON,当我使用Python程序(获取JSON、读取JSON等)时它会工作,但在PHP中它不会获取JSON。你尝试过使用它吗?它也适用于外部URL和POST方法。@AndersCarstensen刚才又尝试了一次,因为它以前不起作用,现在一切都起作用了。非常感谢。
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website

$postdata = http_build_query(
    array(
        'metod' => 'get_number', # misspelled because it is not an English website
        'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
        'country' => 'RU',
        'service' => 'XXXXX'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
print_r($result);