我有一些代码可以从提供的网址获取网页。网址看起来像这样:
这是我用于获取页面的代码:
function GetHtmlContents($url){
echo $url;
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
echo "<br>";
echo $data;
}
但是当我从本地主机运行时,echo $data
是空的,它什么也没显示。
我该如何解决?这是我第一次使用cURL。
答案 0 :(得分:1)
您可以使用此代码获取页面内容
函数GetHtmlContents($ url)
{
$ user_agent =“ Mozilla / 5.0(Windows NT 6.1; rv:8.0)Gecko / 20100101 Firefox / 8.0”;
$options = array(
CURLOPT_CUSTOMREQUEST =>"GET", //set request type post or get
CURLOPT_POST =>false, //set to GET
CURLOPT_USERAGENT => $user_agent, //set user agent
CURLOPT_COOKIEFILE =>"cookie.txt", //set cookie file
CURLOPT_COOKIEJAR =>"cookie.txt", //set cookie jar
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
} print_r(GetHtmlContents('https://www.facebook.com/events/383049449109054/'));
”
答案 1 :(得分:-1)
尝试一下,它应该对您有用。
function GetHtmlContents($url){
echo file_get_contents($url);
}
详细了解file_get_contents()