2012-10-07 107 views
1

我只有一個用於HTML解析的PHP腳本,它適用於簡單的網站,但現在我需要解析this website的電影程序。我正在使用file_get_contents函數,它只返回4個新的行分隔符\n,我只是不明白爲什麼。 由於程序本身只是彈出式窗口,並且它似乎沒有更改URL地址,但我會在檢索HTML代碼後嘗試處理此問題,因此網站本身將更難以用DOMDocument解析XPath現場。PHP file_get_contents僅返回換行

這裏是我的腳本的縮短版:

<?php 
     $url = "http://www.cinemacity.cz/"; 
     $content = file_get_contents($url); 
     $dom = new DomDocument; 
     $dom->loadHTML($content); 

     if ($dom == FALSE) { 
     echo "FAAAAIL\n"; 
     } 

     $xpath = new DOMXPath($dom); 

     $tags = $xpath->query("/html"); 

     foreach ($tags as $tag) { 
     var_dump(trim($tag->nodeValue)); 
     } 
?> 

編輯:

因此,繼WBAR(謝謝)的建議,我一直在尋找一種方式如何改變標題中file_get_contents()函數這是我在其他地方找到的答案。現在我能夠獲得該網站的HTML,希望我將管理這個爛攤子解析:d

<?php 
    libxml_use_internal_errors(true); 
    // Create a stream 
    $opts = array(
     'http'=>array(
     'user_agent' => 'PHP libxml agent', //Wget 1.13.4 
     'method'=>"GET", 
     'header'=>"Accept-language: en\r\n" . 
        "Cookie: foo=bar\r\n" 
    ) 
    ); 
    $context = stream_context_create($opts); 

    // Open the file using the HTTP headers set above 
    $content = file_get_contents('http://www.cinemacity.cz/', false, $context); 

    $dom = new DomDocument; 
    $dom->loadHTML($content); 

    if ($dom == FALSE) { 
     echo "FAAAAIL\n"; 
    } 

    $xpath = new DOMXPath($dom); 

    $tags = $xpath->query("/html"); 

    foreach ($tags as $tag) { 
     var_dump(trim($tag->nodeValue)); 
    } 
?> 
+0

哎呀返回,他們的代碼確實是一個爛攤子。 html之間有很多新行。也許dom解析器被這個困惑了?我不知道。在將它提供給dom解析器之前,在多個換行符上嘗試使用replace_all? – 2012-10-07 11:50:10

+0

如果您使用命令行的默認php config不允許外部URL獲取,請檢查! – xception

回答

4

該問題不在PHP中,而是在目標主機中。它檢測客戶端的User-Aget標題。看看這個:

wget http://www.cinemacity.cz/ 
2012-10-07 13:54:39 (1,44 MB/s) - saved `index.html.1' [234908] 

但是當刪除UserAget標題:

wget --user-agent="" http://www.cinemacity.cz/ 
2012-10-07 13:55:41 (262 KB/s) - saved `index.html.2' [4/4] 

只有4個字節是由服務器

+1

+1爲好的調查努力 – nkr

0

嘗試獲取的內容是這樣的:

function get2url($url, $timeout = 30, $port = 80, $buffer = 128) { 
    $arr = parse_url($url); 
    if(count($arr) < 3) return "URL ERROR"; 

    $ssl = ""; 
    if($arr['scheme'] == "https") $ssl = "ssl://"; 

    $header = "GET " . $arr['path'] . "?" . $arr['query'] . " HTTP/1.0\r\n"; 
    $header .= "Host: " . $arr['host'] . "\r\n"; 
    $header .= "\r\n"; 

    $f = @fsockopen($ssl . $arr['host'], $port, $errno, $errstr, $timeout); 

    if(!$f) 
     return $errstr . " (" . $errno . ")"; 

    else{ 
     @fputs($f, $header . $arr['query']); 

     $echo = ""; 
     while(!feof($f)) { $echo .= @fgets($f, $buffer); } 

     @fclose($f); 

     return $echo; 
    } 
    } 

你將不得不刪除標題雖然。