简体   繁体   English

无法通过使用PHP中的file_get_content获取网站内容

[英]unable to get the website content by using file_get_content in php

When i am trying to get the website content from the external url fanpop.com by using file_get_contents in php, i am getting empty data. 当我尝试通过使用php中的file_get_contents从外部URL fanpop.com获取网站内容时,我正在获取空数据。 I used the below code to get the contents 我用下面的代码来获取内容

$add_url= "http://www.fanpop.com/";  
$add_domain = file_get_contents($add_url);  
echo $add_domain;  

but here i am getting empty result for $add_domain. 但是在这里,我得到了$ add_domain的空结果。 But the same code is working for other urls and i tried to send the request from browser not from the script then also it is not working. 但是相同的代码也适用于其他网址,我尝试从浏览器发送请求而不是从脚本发送请求,因此它也不起作用。

Below is the same request, but in CURL: 以下是相同的请求,但使用CURL:

error_reporting(-1);
ini_set('display_errors','On');
$url="http://www.fanpop.com/";
$ch = curl_init();

$header=array('GET /1575051 HTTP/1.1',
'Host: adfoc.us',
'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language:en-US,en;q=0.8',
'Cache-Control:max-age=0',
'Connection:keep-alive',
'Host:adfoc.us',
'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4)            AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36',
);

curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,0);
curl_setopt( $ch, CURLOPT_COOKIESESSION, true );

curl_setopt($ch,CURLOPT_COOKIEFILE,'cookies.txt');
curl_setopt($ch,CURLOPT_COOKIEJAR,'cookies.txt');
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);

echo $result=curl_exec($ch); echo $ result = curl_exec($ ch);

curl_close($ch);

... but the above is also not working, can any one tell is there any any changes have to make in that? ...但上述方法也不起作用,请问有人可以对它进行任何更改吗?

The problem with this particular site is that it only serves compressed contents and throws a 404 error otherwise. 该特定站点的问题在于,它仅提供压缩内容,否则将引发404错误。

Easy fix: 轻松解决:

$ch = curl_init('http://www.fanpop.com');
curl_setopt($ch,CURLOPT_ENCODING , "");
curl_exec($ch);

You can also make this work for file_get_contents() but with a substantial amount of effort, as described in this article . 您也可以针对file_get_contents()进行此工作,但是要付出很大的努力,如本文所述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM