【问题标题】:get file content returns empty string获取文件内容返回空字符串
【发布时间】:2015-11-23 06:05:09
【问题描述】:

我正在尝试从这里获取内容:

http://t.c4tw.net/MatchUser?hash_key=563b755ac53a3&json=1

$json = file_get_contents('http://t.c4tw.net/MatchUser?hash_key=563b755ac53a3&json=1');
$obj = json_decode($json);
var_dump($json);

结果

string(0) ""

file_get_contents 与其他链接一起工作正常,有没有办法用 php 获取这些数据?

【问题讨论】:

  • 您必须检查提供给file_get_contents() 的路径是否返回有效数据或不为空。
  • 它正在返回 {"twuser_id":"NzE5MTY1NTYwMTg2NjQ5ODI5OA.."}
  • 是的,我用的是&json=1,所以根据api,数据应该是json。
  • 似乎file_get_contents 没有返回任何内容,因为您正在打印它的返回值。你有任何错误吗?可能类似于:stackoverflow.com/questions/19024349/…。我们需要更多信息。
  • var_dump($obj); 返回NULL

标签: php json api


【解决方案1】:

不推荐使用 file_get_contents 从远程源获取内容。更正确的方法是使用 curl。 Curl 可以设置正确的标题、会话、cookie 和其他您无法为 file_get_contents 和 stream_context_set_default 设置的参数

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL,'http://t.c4tw.net/MatchUser?hash_key=563b755ac53a3&json=1');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:42.0) Gecko/20100101 Firefox/42.0');
$curl_response = curl_exec($ch);
curl_close($ch);

$obj = json_decode($curl_response);

var_dump($obj);

结果如下:

object(stdClass)[3341]
public 'twuser_id' => string 'NzU0NDA4MTQwOTU4ODYwNjM3Nw..' (length=28)

【讨论】:

    【解决方案2】:

    不幸的是,PHP 不像 JS 那样支持跨域内容请求,至少开箱即用。要使用 URL 内容请求,必须先设置

    allow_url_fopen
    

    在您的 php.ini 配置文件中。默认情况下,主机通常不允许这样做。

    另外,请确保您转储的是 $obj 而不是 $json。


    另外,您可以查看 PHP 的 cURL library(类似于 JS 的 ajax),它允许跨域请求。

    cURL

    //  Initiate curl
    $ch = curl_init();
    // Disable SSL verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // Return response as string rather than outputting it directly
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // Set cURL url
    curl_setopt($ch, CURLOPT_URL, 'http://t.c4tw.net/MatchUser?hash_key=563b755ac53a3&json=1');
    // Execute request
    $result=curl_exec($ch);
    // Close cURL resource
    curl_close($ch);
    
    // Dump JSON
    var_dump(json_decode($result, true));
    

    【讨论】:

    • 感谢您的回答,我有allow_url_fopen=On 和allow_url_include=On
    • 尝试使用 cURL,我已将其添加到我的答案中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2017-06-14
    • 2014-12-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多