【问题标题】:only the last chunck of contents is returned只返回最后一块内容
【发布时间】:2012-08-16 15:21:02
【问题描述】:
function curl_get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $data = curl_exec($ch);

        print_r(curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD));

        curl_close($ch);
        return $data;
}

我试图将字符串与此页面“wikipedia.sfstate.us/Scarves”进行匹配。我使用函数来获取内容:

$url = "http://wikipedia.sfstate.us/Scarves";
$html = curl_get($url);
var_dump($html);

结果如下:

812 //CURLINFO_SIZE_DOWNLOAD
string(812) "..." //$html string where the content is stored

但是,整个文件是 64612 字节(结果来自 web-sniffer.net)。并且 64612 = 1024 * 63 + 812。也就是说,我只获取文件的最后 812 个字节。

为什么会发生这种情况?关于如何获取全部内容的任何想法?谢谢。

P.S.:我也试过了。如下但没有帮助

if(strlen($html) < 1024){
    $html = '';
    $i = 0;
    while($content = file_get_contents($url, FILE_TEXT,  NULL, $i, $i + 1023)){
            $html .= $content;
            $i += 1023;
    }
}

【问题讨论】:

    标签: php curl file-get-contents


    【解决方案1】:

    您尝试抓取的页面具有基于用户代理的保护。向您的请求添加适当的用户代理,它就可以工作:

    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
    

    当然,如果他们有这样的保护,那可能是因为他们不想让你抓取他们的内容。

    【讨论】:

      【解决方案2】:

      试试这是我测试过的代码,它工作正常

      输出:-

      <?php
      
      function curl_get($url){
              $ch = curl_init();
              curl_setopt($ch, CURLOPT_HEADER, true); 
              curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
              curl_setopt($ch, CURLOPT_URL, $url);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
              $data = curl_exec($ch);
      
              print_r(curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD));
      
              curl_close($ch);
              return $data;
      }
      
      
      $url = "http://wikipedia.sfstate.us/Scarves";
      $html = curl_get($url);
      var_dump($html); 
      

      也试试另一个例子

      $ch = curl_init("http://wikipedia.sfstate.us/Scarves");
      $fp = fopen("example_htmlpage.html", "w");
      
      curl_setopt($ch, CURLOPT_FILE, $fp);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_exec($ch);
      curl_close($ch);
      fclose($fp);
      

      【讨论】:

        猜你喜欢
        • 2022-01-11
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 2014-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-15
        相关资源
        最近更新 更多