php json 返回 bool(false)
关于为什么以下不起作用的任何想法。
$request_url = "someurl?myId=$id"; //returns feed like above
$json = file_get_contents($request_url, true); //getting the file content
$decode = json_decode($json, true);
var_dump($json);
当我将 request_url 粘贴到浏览器中时,我会返回 json 数据,但如果我在 php 中尝试,var_dump 只是 bool(false);有什么想法吗?
更新和修复 好的,谢谢大家的帮助。叶帮我找到了这个。事实证明,php.ini 配置为禁止打开 url,因此 file_get_contents 不起作用。我在各个网站上发现了以下方便的功能,并使用了它,以便对其进行排序。这是我使用的方法,以防对其他人有所帮助。
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Any thoughts as to why the following is not working.
$request_url = "someurl?myId=$id"; //returns feed like above
$json = file_get_contents($request_url, true); //getting the file content
$decode = json_decode($json, true);
var_dump($json);
When I paste the request_url into a browser I get back the json data but if I try in php the var_dump is simply bool(false); Any ideas??
Update and fix
OK guys thanks for all the help. Ye helped me track this one down. It turned out to be the php.ini is configured to disallow the opening of urls so the file_get_contents would not work. I found the following handy function mentioned on various sites and used it so its sorted. Here is the method I used in case it helps someone else.
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我复制了你的问题,当 ajax url 错误(未找到)时,我观察到 bool(false) 。
确保您的“someurl”有效。
如果 JSON 无效,您的脚本仍会正确打印它。
如果 url 没有返回任何内容,您仍然会观察到 'string(0) ""'
问题是无效的 url。
I replicated your problem and I observe bool(false) when the ajax url is wrong (not found).
Make sure your "someurl" is valid.
If the JSON is invalid, your script would still print it correctly.
If the url returns nothing you's still observe 'string(0) ""'
The issue is the invalid url.
也许 $request_url 的响应字符集不是“utf-8”或“ansi”。
maybe the response's charset of $request_url is not 'utf-8' or 'ansi'.
根据 PHP 文档,file_get_contents 在失败时返回 false。这意味着该 url 无效或无法从 php 访问。
如果您从服务器尝试此操作,请确保您的防火墙没有阻止此传出流量。
According to the PHP documentation, file_get_contents returns false on failure. This means that the url is not valid or can not be accessed from php.
If you are trying this from a server, be sure that your firewall is not blocking this outgoing traffic.