php:file_get_contents编码问题

时间:2009-04-03 09:54:07

标签: php encoding file-get-contents

我的任务很简单:向translate.google.com发帖请求并获取翻译。 在下面的例子中,我使用“hello”这个词翻译成俄语。

header('Content-Type: text/plain; charset=utf-8');  // optional
error_reporting(E_ALL | E_STRICT);

$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => implode("\r\n", array(
            'Content-type: application/x-www-form-urlencoded',
            'Accept-Language: en-us,en;q=0.5', // optional
            'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7' // optional
        )),
        'content' => http_build_query(array(
            'prev'  =>  '_t',
            'hl'    =>  'en',
            'ie'    =>  'UTF-8',
            'text'  =>  'hello',
            'sl'    =>  'en',
            'tl'    =>  'ru'
        ))
    )
));

$page = file_get_contents('http://translate.google.com/translate_t', false, $context);

require '../simplehtmldom/simple_html_dom.php';
$dom = str_get_html($page);
$translation = $dom->find('#result_box', 0)->plaintext;
echo $translation;

标记为可选的行是那些没有输出相同的行。但我得到了奇怪的人物......

������

我试过

echo mb_convert_encoding($translation, 'UTF-8');

但是我得到了

ÐÒÉ×ÅÔ

有人知道如何解决这个问题吗?

更新:

  1. 忘记提及我所有的PHP 文件以UTF-8编码而没有 BOM
  2. 当我改变“to”语言时 到“en”,即从中翻译出来 英语到英语,它运作正常。
  3. 我不认为我正在使用的库正在弄乱它,因为我试图输出整个$页面而不将其传递给库函数。
  4. 我正在使用PHP 5

3 个答案:

答案 0 :(得分:9)

首先,您的浏览器是否设置为UTF-8?在Firefox中,您可以在View-> Character Encoding中设置文本编码。确保选中“Unicode(UTF-8)”。我还将View-> Character Encoding-> Auto-Detect设置为“Universal。”

其次,您可以尝试传递FILE_TEXT标志,如下所示:

$page = file_get_contents('http://translate.google.com/translate_t', FILE_TEXT, $context);

答案 1 :(得分:8)

尝试查看此帖子是否可以帮助CURL import character encoding problem

你也可以尝试这个片段(取自php.net)

<?php
function file_get_contents_utf8($fn) {
     $content = file_get_contents($fn);
      return mb_convert_encoding($content, 'UTF-8',
          mb_detect_encoding($content, 'UTF-8, ISO-8859-1', true));
}
?>

答案 2 :(得分:1)

Accept-Charset 实际上不是可选的。你应该在那里指定UTF8。俄语字符在ISO_8859-1中无效