2010-07-31 93 views
1

我怎樣才能得到HTML網頁字符集編碼從HTML作爲字符串,而不是作爲DOM?我怎樣才能得到HTML網頁字符集編碼從HTML作爲字符串,而不是作爲DOM?

我得到的html串那樣:

$html = file_get_contents($url); 
preg_match_all (string pattern, string subject, array matches, int flags) 

但我不知道正則表達式,我需要找出網頁字符集(UTF-8/Windows的255 /等。) 謝謝,

+1

您應該首先檢查HTTP標頭的字符編碼,並且僅在缺少後檢查HTML。 – Gumbo 2010-07-31 21:27:36

回答

6

的preg_match( '〜字符集=([ - 一個-Z0-9 _] +)〜I',$ HTML,$字符集);

+0

這似乎假設'$ html'包含http頭,但它沒有。 – mvds 2010-07-31 21:38:52

+1

請不要。如果我碰巧解析了一個解釋如何定義頁面編碼的頁面?...... – Artefacto 2010-07-31 21:40:34

+0

...那麼你會發現它會被編碼爲什麼? – 2010-07-31 21:41:34

0

可以使用

mb_detect_encoding($html); 

,但它通常是一個壞主意。更好地使用curl,然後查看Content-Type標題。

+0

我知道mb_detect_encoding($ html)工作不正常。 – Yosef 2010-07-31 21:32:12

+0

然後可能*「改爲使用curl並查看Content-Type標題」* – mvds 2010-07-31 21:36:35

1

首先你必須檢查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], '"'); 
      } 
     } 
    } 
} 
+0

模式分隔符和區分大小寫是怎麼回事? – mvds 2010-07-31 21:33:01

+0

正則表達式沒有分界,貪婪的捕獲會給你很多比你想要的更多 – 2010-07-31 21:33:56

+0

爲什麼不使用file_get_contents而不是fopen? 我需要得到HTML到其他tesk後 – Yosef 2010-07-31 21:34:03

相關問題