【问题标题】:php: file_get_contents(url) failed to open stream when calling a page that has a json responsephp:调用具有 json 响应的页面时,file_get_contents(url) 无法打开流
【发布时间】:2015-08-11 03:53:34
【问题描述】:

我有以下代码:

<?php
//first try
$url = 'http://www.omdbapi.com';
echo '<pre>';
print_r(file_get_contents($url));
echo '</pre>';


//second try
$url = 'http://www.omdbapi.com/?t=the dark night';
echo '<pre>';
print_r(file_get_contents($url));
echo '</pre>';
?>

第一次尝试效果很好。但是,第二次尝试给出以下错误消息,没有更多详细信息: $file_get_contents(http://www.omdbapi.com/?t=the dark night): failed to open stream: HTTP request failed!

请注意,pc 有 windows 8.1 x64,我已经尝试过 wamp server 和 xampp。我确实确保两个 $php.ini 文件都启用了扩展 $extension=php_openssl.dll$extension=php_curl.dll

【问题讨论】:

  • 尝试用%20替换你的url中的空格。

标签: php json codeigniter


【解决方案1】:

尝试使用urlencode 对您的网址进行编码:

$url = 'http://www.omdbapi.com/?t='.urlencode('the dark night');
echo '<pre>';
print_r(file_get_contents($url));
echo '</pre>';

【讨论】:

    【解决方案2】:

    file_get_contents的文档说

    注意:如果您打开一个带有特殊字符(例如空格)的 URI,您 需要用urlencode()对URI进行编码。

    所以替换

    $url = 'http://www.omdbapi.com/?t=the dark night';
    

    $url = 'http://www.omdbapi.com/?t='.urlencode('the dark night');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-10-02
      • 2017-03-15
      相关资源
      最近更新 更多