Php 获取文件内容返回空字符串
我正在尝试从这里获取内容: 结果Php 获取文件内容返回空字符串,php,json,api,Php,Json,Api,我正在尝试从这里获取内容: 结果 string(0) "" 文件\u get\u内容与其他链接配合良好,有没有办法用php获取这些数据?不幸的是,php不像JS那样支持跨域内容请求,至少是开箱即用。若要使用URL内容请求,必须首先设置 allow_url_fopen 在php.ini配置文件中。默认情况下,主机通常不允许这样做 另外,确保您正在转储$obj而不是$json 此外,您还可以研究PHP(类似于JS的ajax),它允许跨域请求 文件\u获取\u内容不建议从远程源获取内容。更正确
string(0) ""
文件\u get\u内容与其他链接配合良好,有没有办法用php获取这些数据?不幸的是,php不像JS那样支持跨域内容请求,至少是开箱即用。若要使用URL内容请求,必须首先设置
allow_url_fopen
在php.ini配置文件中。默认情况下,主机通常不允许这样做
另外,确保您正在转储$obj而不是$json
此外,您还可以研究PHP(类似于JS的ajax),它允许跨域请求
文件\u获取\u内容不建议从远程源获取内容。更正确的方法是使用curl。Curl可能会设置正确的头、会话、cookie和其他参数,而这些参数是您无法为file\u get\u contents和stream\u context\u set\u 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)
您必须检查提供给
file_get_contents()
的路径是否返回有效数据或它不是空的。它返回的是{“twuser_id”:“nze5mtyanytwmtg2njq5odi5oa..”}是的,我使用的是&json=1
,因此根据api,数据应该是json格式。似乎file\u get\u contents
没有返回任何内容,因为您正在打印它的返回值。你有什么错误吗?可能是这样的。我们需要更多信息。var_dump($obj)
返回NULL
谢谢你的回答,我有allow\u url\u fopen=On
和allow\u url\u include=On
尝试使用cURL,我已将它添加到我的答案中
$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)