首先你必須檢查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 2010-07-31 21:27:36