问题描述
当我尝试运行我的PHP脚本时出现以下错误:
I'm getting the following error when I try to run my PHP script:
我的代码如下:
<?php
$json = json_decode(file_get_contents('prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=*key*'));
print_r($json);
?>
注意: * key *
是替代品对于URL中的字符串(我的API密钥),并且出于隐私原因而被隐藏。
Note: *key*
is a replacement for a string in the URL (my API key) and has been hidden for privacy reasons.
我删除了 https://
从URL中获取一个错误消失。
I removed the https://
from the URL to get one error to disappear.
我在这里做错了吗?也许URL?
Am I doing something wrong here? Maybe the URL?
推荐答案
URL缺少协议信息。 PHP认为它是一个文件系统路径,并尝试访问指定位置的文件。但是,该位置实际上并不存在于您的文件系统中,并且会引发错误。
The URL is missing the protocol information. PHP thinks it is a filesystem path and tries to access the file at the specified location. However, the location doesn't actually exist in your filesystem and an error is thrown.
您需要添加 http
或 https
在URL的开头,你试图从以下内容获取内容:
You'll need to add http
or https
at the beginning of the URL you're trying to get the contents from:
$json = json_decode(file_get_contents('http://...'));
至于以下错误:
您的Apache安装可能没有使用SSL支持编译。您可以手动尝试安装OpenSSL并使用它,或使用cURL。我个人更喜欢cURL超过 file_get_contents()
。这是一个你可以使用的函数:
Your Apache installation probably wasn't compiled with SSL support. You could manually try to install OpenSSL and use it, or use cURL. I personally prefer cURL over file_get_contents()
. Here's a function you can use:
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
用法:
$url = 'https://...';
$json = json_decode(curl_get_contents($url));
这篇关于file_get_contents()如何修复错误“无法打开流”,“没有这样的文件”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!