2012-10-07 109 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; 
    } 
    } 

你将不得不删除标题虽然。