2011-04-08 30 views
3

我試圖從yahoo.com獲取搜索結果。file_get_contents()將UTF-8轉換爲ISO-8859-1

但是 file_get_contents()將UTF-8字符集(yahoo使用的charset)內容轉換爲ISO-8859-1。

嘗試:

$filename = "http://search.yahoo.com/search;_ylt=A0oG7lpgGp9NTSYAiQBXNyoA?p=naj%C5%A1%C5%A5astnej%C5%A1%C3%AD&fr2=sb-top&fr=yfp-t-701&type_param=&rd=pref"; 

echo file_get_contents($filename); 

腳本作爲

header('Content-Type: text/html; charset=UTF-8'); 

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 

$er = mb_convert_encoding($filename , 'UTF-8'); 

$s2 = iconv("ISO-8859-1","UTF-8",$filename); 

echo utf8_encode(file_get_contents($filename)); 

沒有幫助,因爲讓網頁內容speciall字符式T z是用問號代替後???

我將不勝感激任何形式的幫助。

+0

** file_get_contents()不會轉換任何內容** – 2011-04-09 11:35:32

回答

7

這似乎是content negotiation問題,因爲file_get_contents可能會發送一個請求,只接受ISO 8859-1作爲字符編碼。

$opts = array('http' => array('header' => 'Accept-Charset: UTF-8, *;q=0')); 
$context = stream_context_create($opts); 

$filename = "http://search.yahoo.com/search;_ylt=A0oG7lpgGp9NTSYAiQBXNyoA?p=naj%C5%A1%C5%A5astnej%C5%A1%C3%AD&fr2=sb-top&fr=yfp-t-701&type_param=&rd=pref"; 
echo file_get_contents($filename, false, $context); 
+0

是的,這工作!非常感謝你!!! :) – vladinko0 2011-04-09 11:41:56

+0

有趣的事情,我試過'Accept-Charset = utf-8; q = 0.7,*; q = 0.7',但不起作用:) – 2011-04-09 11:57:28

+0

@webarto:值'utf-8; q = 0.7, *; q = 0.7'就像'utf-8,*'並且可以接受任何相同的字符編碼。 – Gumbo 2011-04-09 12:09:02

0
$s2 = iconv("ISO-8859-1","UTF-8//TRANSLIT//IGNORE",$filename); 

更好的解決方案...

function curl($url){ 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    curl_setopt($ch, CURLOPT_ENCODING, 1); 
    return curl_exec($ch); 
    curl_close($ch); 
} 

echo curl($filename); 
+0

結果是:文檔已移至此處。 – vladinko0 2011-04-09 10:48:41

+0

@ vladinko0,我想你需要設置'CURLOPT_FOLLOWLOCATION',我已經更新了我的答案,再試一次。 – 2011-04-09 11:17:22

+0

現在它加載頁面,但與file_get_contents()具有相同的結果,這意味着帶有問號。字符集也轉換爲ISO-8859-1。 – vladinko0 2011-04-09 11:32:07

3

的file_get_contents應該變化的字符集。數據以二進制字符串形式提取。

當檢查出您所提供的,這是它提供了頭:

Content-Type: text/html; charset=ISO-8859-1 

此外,在機身:

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> 

而且,你不能轉換UTF-8無損轉換爲ISO-8859-1並返回到UTF-8時返回字符。 UTF-8/unicode支持很多更多的字符,所以在第一步中字符會丟失。

在瀏覽器中,情況並非如此,所以也許您只需要提供一個正確的Accept-Encoding標頭來指示雅虎的系統可以接受UTF-8。

+0

你是如何找出'Content-Type:text/html; charset = ISO-8859-1'和'' 當我查看該頁面的源代碼時請參閱<!doctype html>' – vladinko0 2011-04-09 10:59:14

+0

它根據您的位置,你可以嘗試使用俄羅斯代理服務器獲取頁面。 – 2011-04-09 11:56:23

1

對於任何調查這個:

我的編碼問題花費的時間教我

可以使用stream_context_create明確指出您接受UTF-8創建自定義stream contextfile_get_contents很少有PHP函數「神奇地」改變字符串的編碼。 (其中一個罕見的例子是:

exec($command, $output, $returnVal)

也請注意,工作頭設置如下:

header('Content-Type: text/html; charset=utf-8');

,而不是:

header('Content-Type: text/html; charset=UTF-8');

因爲我也有類似的問題,因爲一個你描述,它足以正確設置標題。

希望這有助於!