먼저 Content-type 헤더를 확인해야합니다.
//add error handling
$f = fopen($url, "r");
$md = stream_get_meta_data($f);
$wd = $md["wrapper_data"];
foreach($wd as $response) {
if (preg_match('/^content-type: .+?/.+?;\\s?charset=([^;"\\s]+|"[^;"]+")/i',
$response, $matches) {
$charset = $matches[1];
break;
}
}
$data = stream_get_contents($f);
그런 다음 meta
요소에 폴백 할 수 있습니다. 그것은 here 전에 답변되었습니다. 관객 기쁘게 분석 헤더의
더 복잡한 버전 :
if (preg_match('~^content-type: .+?/[^;]+?(.*)~i', $response, $matches)) {
if (preg_match_all('~;\\s?(?P<key>[^()<>@,;:\"/[\\]?={}\\s]+)'.
'=(?P<value>[^;"\\s]+|"[^;"]+")\\s*~i', $matches[1], $m)) {
for ($i = 0; $i < count($m['key']); $i++) {
if (strtolower($m['key'][$i]) == "charset") {
$charset = trim($m['value'][$i], '"');
}
}
}
}
먼저 HTTP 헤더에서 문자 인코딩을 확인하고 누락 된 경우에만 HTML을 확인해야합니다. – Gumbo