찾다
백엔드 개발PHP 튜토리얼php file_get_contents抓取Gzip网页乱码的三种解决方法_php实例

把抓取到的内容转下编码即可($content=iconv("GBK", "UTF-8//IGNORE", $content);),我们这里讨论的是如何抓取开了Gzip的页面。怎么判断呢?获取的头部当中有Content-Encoding: gzip说明内容是GZIP压缩的。用FireBug看一下就知道页面开了gzip没有。下面是用firebug查看我的博客的头信息,Gzip是开了的。

复制代码 代码如下:

请求头信息原始头信息
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3
Connection keep-alive
Cookie __utma=225240837.787252530.1317310581.1335406161.1335411401.1537; __utmz=225240837.1326850415.887.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=%E4%BB%BB%E4%BD%95%E9%A1%B9%E7%9B%AE%E9%83%BD%E4%B8%8D%E4%BC%9A%E9%82%A3%E4%B9%88%E7%AE%80%E5%8D%95%20site%3Awww.nowamagic.net; PHPSESSID=888mj4425p8s0m7s0frre3ovc7; __utmc=225240837; __utmb=225240837.1.10.1335411401
Host www.nowamagic.net
User-Agent Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0

下面介绍一些解决方案:

1. 使用自带的zlib库
如果服务器已经装了zlib库,用下面的代码可以轻易解决乱码问题。

复制代码 代码如下:

$data = file_get_contents("compress.zlib://".$url);

2. 使用CURL代替file_get_contents

复制代码 代码如下:

function curl_get($url, $gzip=false){
 $curl = curl_init($url);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
 if($gzip) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); // 关键在这里
 $content = curl_exec($curl);
 curl_close($curl);
 return $content;
}

3. 使用gzip解压函数

复制代码 代码如下:

function gzdecode($data) {
  $len = strlen($data);
  if ($len     return null;  // Not GZIP format (See RFC 1952)
  }
  $method = ord(substr($data,2,1));  // Compression method
  $flags  = ord(substr($data,3,1));  // Flags
  if ($flags & 31 != $flags) {
    // Reserved bits are set -- NOT ALLOWED by RFC 1952
    return null;
  }
  // NOTE: $mtime may be negative (PHP integer limitations)
  $mtime = unpack("V", substr($data,4,4));
  $mtime = $mtime[1];
  $xfl   = substr($data,8,1);
  $os    = substr($data,8,1);
  $headerlen = 10;
  $extralen  = 0;
  $extra     = "";
  if ($flags & 4) {
    // 2-byte length prefixed EXTRA data in header
    if ($len - $headerlen - 2       return false;    // Invalid format
    }
    $extralen = unpack("v",substr($data,8,2));
    $extralen = $extralen[1];
    if ($len - $headerlen - 2 - $extralen       return false;    // Invalid format
    }
    $extra = substr($data,10,$extralen);
    $headerlen += 2 + $extralen;
  }

  $filenamelen = 0;
  $filename = "";
  if ($flags & 8) {
    // C-style string file NAME data in header
    if ($len - $headerlen - 1       return false;    // Invalid format
    }
    $filenamelen = strpos(substr($data,8+$extralen),chr(0));
    if ($filenamelen === false || $len - $headerlen - $filenamelen - 1       return false;    // Invalid format
    }
    $filename = substr($data,$headerlen,$filenamelen);
    $headerlen += $filenamelen + 1;
  }

  $commentlen = 0;
  $comment = "";
  if ($flags & 16) {
    // C-style string COMMENT data in header
    if ($len - $headerlen - 1       return false;    // Invalid format
    }
    $commentlen = strpos(substr($data,8+$extralen+$filenamelen),chr(0));
    if ($commentlen === false || $len - $headerlen - $commentlen - 1       return false;    // Invalid header format
    }
    $comment = substr($data,$headerlen,$commentlen);
    $headerlen += $commentlen + 1;
  }

  $headercrc = "";
  if ($flags & 1) {
    // 2-bytes (lowest order) of CRC32 on header present
    if ($len - $headerlen - 2       return false;    // Invalid format
    }
    $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff;
    $headercrc = unpack("v", substr($data,$headerlen,2));
    $headercrc = $headercrc[1];
    if ($headercrc != $calccrc) {
      return false;    // Bad header CRC
    }
    $headerlen += 2;
  }

  // GZIP FOOTER - These be negative due to PHP's limitations
  $datacrc = unpack("V",substr($data,-8,4));
  $datacrc = $datacrc[1];
  $isize = unpack("V",substr($data,-4));
  $isize = $isize[1];

  // Perform the decompression:
  $bodylen = $len-$headerlen-8;
  if ($bodylen     // This should never happen - IMPLEMENTATION BUG!
    return null;
  }
  $body = substr($data,$headerlen,$bodylen);
  $data = "";
  if ($bodylen > 0) {
    switch ($method) {
      case 8:
        // Currently the only supported compression method:
        $data = gzinflate($body);
        break;
      default:
        // Unknown compression method
        return false;
    }
  } else {
    // I'm not sure if zero-byte body content is allowed.
    // Allow it for now...  Do nothing...
  }

  // Verifiy decompressed size and CRC32:
  // NOTE: This may fail with large data sizes depending on how
  //       PHP's integer limitations affect strlen() since $isize
  //       may be negative for large sizes.
  if ($isize != strlen($data) || crc32($data) != $datacrc) {
    // Bad format!  Length or CRC doesn't match!
    return false;
  }
  return $data;
}


使用:
复制代码 代码如下:

$html=file_get_contents('http://www.jb51.net/');
$html=gzdecode($html);

就介绍这三个方法,应该能解决大部分gzip引起的抓取乱码问题了。
성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
PHP 응용 프로그램을 더 빨리 만드는 방법PHP 응용 프로그램을 더 빨리 만드는 방법May 12, 2025 am 12:12 AM

TomakePhPapplicationSfaster, followthesesteps : 1) useopCodeCaching likeOpcachetOrpectipiledScriptBecode.2) MinimizedAtabaseQueriesByUsingQueryCachingandEfficientIndexing.3) leveragephp7 assistorBetterCodeeficiession.4) 구현 전략적 지시

PHP 성능 최적화 점검표 : 지금 속도를 향상시킵니다PHP 성능 최적화 점검표 : 지금 속도를 향상시킵니다May 12, 2025 am 12:07 AM

toImprovePhPapplicationSpeed, followthesesteps : 1) enableOpCodeCachingWithApcuTeCeScripteXecutionTime.2) 구현 구현

PHP 의존성 주입 : 코드 테스트 가능성을 향상시킵니다PHP 의존성 주입 : 코드 테스트 가능성을 향상시킵니다May 12, 2025 am 12:03 AM

의존성 주입 (DI)은 명시 적으로 전이적 종속성에 의해 PHP 코드의 테스트 가능성을 크게 향상시킵니다. 1) DI 디퍼 커플 링 클래스 및 특정 구현은 테스트 및 유지 보수를보다 유연하게 만듭니다. 2) 세 가지 유형 중에서, 생성자는 상태를 일관성있게 유지하기 위해 명시 적 표현 의존성을 주입합니다. 3) DI 컨테이너를 사용하여 복잡한 종속성을 관리하여 코드 품질 및 개발 효율성을 향상시킵니다.

PHP 성능 최적화 : 데이터베이스 쿼리 최적화PHP 성능 최적화 : 데이터베이스 쿼리 최적화May 12, 2025 am 12:02 AM

DatabaseQuesyOptimizationInphPinVolvesVesstoigiestoInsperferferferferformance.1) SelectOnlyNecessaryColumnstoredAtatatransfer.2) useinDexingTeSpeedUpdatarretieval.3) ubstractOrerEresultSoffRequeries.4) UtilizePreDstatements Offeffi

간단한 가이드 : PHP 스크립트와 함께 이메일 보내기간단한 가이드 : PHP 스크립트와 함께 이메일 보내기May 12, 2025 am 12:02 AM

phpisusedforendingemailsduetoitsbuitsbuitsbuit-inmail () functionandsupportivelibraries lifephpmailerandswiftmailer.1) usethemail () functionforbasicemails, butithaslimitations.2) EmployPhpmailerforAdvancedFeatirehtMailsAndAtachments.3))

PHP 성능 : 병목 현상 식별 및 수정PHP 성능 : 병목 현상 식별 및 수정May 11, 2025 am 12:13 AM

PHP 성능 병목 현상은 다음 단계를 통해 해결할 수 있습니다. 1) 성능 분석을 위해 Xdebug 또는 Blackfire를 사용하여 문제를 찾으십시오. 2) 데이터베이스 쿼리 최적화 및 APCU와 같은 캐시 사용; 3) Array_Filter와 같은 효율적인 기능을 사용하여 배열 작업을 최적화합니다. 4) 바이트 코드 캐시에 대한 OpCache 구성; 5) HTTP 요청을 줄이고 사진 최적화와 같은 프론트 엔드 최적화; 6) 지속적으로 모니터링하고 성능을 최적화합니다. 이러한 방법을 통해 PHP 응용 프로그램의 성능을 크게 향상시킬 수 있습니다.

PHP의 종속성 주입 : 빠른 요약PHP의 종속성 주입 : 빠른 요약May 11, 2025 am 12:09 AM

종속성 주사 (di) inphpisadesignpattern thatmanages 및 enpleducesclassdelencies, 향상 codemodularity, trestability 및 maintainability .itallowspassingDepporsingDikedAbaseConnectionStoclassesAssparameters, 촉진 이용성.

PHP 성능 향상 : 캐싱 전략 및 기술PHP 성능 향상 : 캐싱 전략 및 기술May 11, 2025 am 12:08 AM

cachingimprovesphpperferferfermanceStoringResultsOfcomputationSorqueriesforquickRetrieval, retingServerloadandenhancancing responsetimestimes : 1) opcodecaching, opcodecaching, whitescompiledphps scriptsinmorytoskipcompileation; 2) dataCachingUsingmemmc

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음