2011-08-01 148 views
3

我期待構建一個解析特定標籤HTML的PHP​​腳本。我一直在使用這個代碼塊,改編自該tutorialfile_get_contents腳本適用於某些網站,但不適用於其他人

<?php 
$data = file_get_contents('http://www.google.com'); 
$regex = '/<title>(.+?)</'; 
preg_match($regex,$data,$match); 
var_dump($match); 
echo $match[1]; 
?> 

腳本與一些網站的工作(如谷歌,以上),但是當我嘗試它與其他網站(比如說,新鮮直達)我得到這個錯誤:

「Warning:file_get_contents(http://www.freshdirect.com)[function.file-get-contents]:無法打開流:HTTP請求失敗!」

我在StackOverflow上看到很多suggestions,例如在php.ini中啓用extension=php_openssl.dll。但是(1)我的php.ini版本沒有extension=php_openssl.dll,並且(2)當我將它添加到擴展部分並重新啓動WAMP服務器時,根據這個thread,仍然沒有成功。

有人會指出我在正確的方向嗎?非常感謝你!

+1

也許看看嫋嫋喜歡上了這一個:http://stackoverflow.com/questions/697472/file-get-contents-returning-failed-to-open-stream-http-request-failed – MaxiWheat

回答

3
$html = file_get_html('http://google.com/'); 
$title = $html->find('title')->innertext; 

或者,如果你喜歡用的preg_match,你應該用真正的捲曲而不是FGC ...

function curl($url){ 

    $headers[] = "User-Agent:Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13"; 
    $headers[] = "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
    $headers[] = "Accept-Language:en-us,en;q=0.5"; 
    $headers[] = "Accept-Encoding:gzip,deflate"; 
    $headers[] = "Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.7"; 
    $headers[] = "Keep-Alive:115"; 
    $headers[] = "Connection:keep-alive"; 
    $headers[] = "Cache-Control:max-age=0"; 

    $curl = curl_init(); 
    curl_setopt($curl, CURLOPT_URL, $url); 
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($curl, CURLOPT_ENCODING, "gzip"); 
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); 
    $data = curl_exec($curl); 
    curl_close($curl); 
    return $data; 

} 


$data = curl('http://www.google.com'); 
$regex = '#<title>(.*?)</title>#mis'; 
preg_match($regex,$data,$match); 
var_dump($match); 
echo $match[1]; 
+0

只有使用簡單的html dom,如果你沒有[更快的替代方案]之間的選擇(http://stackoverflow.com/questions/3577641/best-methods-to-parse-html-with-php/3577662# 3577662) – Wrikken

+0

@Wrikken,在哪些方面更快? –

+0

DOM解析和一般搜索/更改DOM(但它可能有點冗長,做一些實際的改動,如果它不用於DOM,因此鏈接到包的答案,使它像simplehtmldom一樣簡單,但仍然使用dom/libxml用於更快的處理)。 – Wrikken

3

它只是需要一個用戶代理(「任何」真的,任何字符串就足夠了) :

file_get_contents("http://www.freshdirect.com",false,stream_context_create(
    array("http" => array("user_agent" => "any")) 
)); 

請參閱more options

當然,你也可以在您的INI設置user_agent

ini_set("user_agent","any"); 
echo file_get_contents("http://www.freshdirect.com"); 

...但我寧願是明確的下一個程序員做這個工作。

+0

謝謝 - 非常感謝! –

0

另一種選擇:有些主機禁用CURLOPT_FOLLOWLOCATION所以遞歸是你想要的,也會登錄到文本文件中的任何錯誤。另外一個簡單的例子就是如何使用DOMDocument()來提取內容,顯然它不是廣泛的,但可以構建appon。

<?php 
function file_get_site($url){ 
(function_exists('curl_init')) ? '' : die('cURL Must be installed. Ask your host to enable it or uncomment extension=php_curl.dll in php.ini'); 
$curl = curl_init(); 
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,"; 
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; 
$header[] = "Cache-Control: max-age=0"; 
$header[] = "Connection: keep-alive"; 
$header[] = "Keep-Alive: 300"; 
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"; 
$header[] = "Accept-Language: en-us,en;q=0.5"; 
$header[] = "Pragma: "; 

curl_setopt($curl, CURLOPT_URL, $url); 
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0 Firefox/5.0'); 
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
curl_setopt($curl, CURLOPT_HEADER, true); 
curl_setopt($curl, CURLOPT_REFERER, $url); 
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate'); 
curl_setopt($curl, CURLOPT_AUTOREFERER, true); 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_TIMEOUT, 60); 

$html = curl_exec($curl); 

$status = curl_getinfo($curl); 
curl_close($curl); 

if($status['http_code']!=200){ 
    if($status['http_code'] == 301 || $status['http_code'] == 302) { 
     list($header) = explode("\r\n\r\n", $html, 2); 
     $matches = array(); 
     preg_match("/(Location:|URI:)[^(\n)]*/", $header, $matches); 
     $url = trim(str_replace($matches[1],"",$matches[0])); 
     $url_parsed = parse_url($url); 
     return (isset($url_parsed))? file_get_site($url):''; 
    } 
    $oline=''; 
    foreach($status as $key=>$eline){$oline.='['.$key.']'.$eline.' ';} 
    $line =$oline." \r\n ".$url."\r\n-----------------\r\n"; 
    $handle = @fopen('./curl.error.log', 'a'); 
    fwrite($handle, $line); 
    return FALSE; 
} 
return $html; 
} 


function get_content_tags($source,$tag,$id=null,$value=null){ 
    $xml = new DOMDocument(); 
    @$xml->loadHTML($source); 

    foreach($xml->getElementsByTagName($tag) as $tags) { 
     if($id!=null){ 
      if($tags->getAttribute($id)==$value){ 
       return $tags->getAttribute('content'); 
      } 
     } 
     return $tags->nodeValue; 
    } 
} 


$source = file_get_site('http://www.freshdirect.com/about/index.jsp'); 

echo get_content_tags($source,'title'); //FreshDirect 

echo get_content_tags($source,'meta','name','description'); //Online grocer providing high quality fresh...... 

?> 
+0

謝謝@lawrence! –

相關問題