PHP 无法从本地页面获取 json,只能从远程 url
PHP can't get json from local page, only remote url
我目前正在使用 Slim 框架构建网站。我在我的站点上设置了端点并且它正在运行,但是当尝试使用 PHP file_get_contents()
和 json_decode()
获取它时,没有任何返回。当我 运行 相同的代码但将 url 更改为远程 public API 时,json 被解码并输出到页面。
工作代码
$url = "https://jsonplaceholder.typicode.com/users";
$contents = file_get_contents($url);
$results = json_decode($contents); // Returns JSON array
不适用于本地站点
$url = "https://local/api/endpoint";
$contents = file_get_contents($url);
$results = json_decode($contents); // Returns NULL
关于可能导致此问题的任何想法?可能 headers?
您的本地端点失败,因为 php 在您使用自签名证书的情况下无法验证 SSL 证书。在本地开发中,您可以通过修改默认流上下文来绕过 SSL CA 检查:
$stream_opts = [
"ssl" => [
"verify_peer"=>false,
"verify_peer_name"=>false,
]
];
$response = file_get_contents("https://local/api/endpoint",
false, stream_context_create($stream_opts));
我目前正在使用 Slim 框架构建网站。我在我的站点上设置了端点并且它正在运行,但是当尝试使用 PHP file_get_contents()
和 json_decode()
获取它时,没有任何返回。当我 运行 相同的代码但将 url 更改为远程 public API 时,json 被解码并输出到页面。
工作代码
$url = "https://jsonplaceholder.typicode.com/users";
$contents = file_get_contents($url);
$results = json_decode($contents); // Returns JSON array
不适用于本地站点
$url = "https://local/api/endpoint";
$contents = file_get_contents($url);
$results = json_decode($contents); // Returns NULL
关于可能导致此问题的任何想法?可能 headers?
您的本地端点失败,因为 php 在您使用自签名证书的情况下无法验证 SSL 证书。在本地开发中,您可以通过修改默认流上下文来绕过 SSL CA 检查:
$stream_opts = [
"ssl" => [
"verify_peer"=>false,
"verify_peer_name"=>false,
]
];
$response = file_get_contents("https://local/api/endpoint",
false, stream_context_create($stream_opts));