Jam*_*mol 8 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;
Run Code Online (Sandbox Code Playgroud)
标记为可选的行是那些没有输出相同的行.但我得到了奇怪的人物......
??????
Run Code Online (Sandbox Code Playgroud)
我试过了
echo mb_convert_encoding($translation, 'UTF-8');
Run Code Online (Sandbox Code Playgroud)
但我明白了
ÐÒÉ×ÅÔ
Run Code Online (Sandbox Code Playgroud)
有人知道如何解决这个问题吗?
更新:
Ale*_*ekc 10
如果它可以帮助CURL导入字符编码问题,请尝试查看此帖子
你也可以尝试这个片段(取自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));
}
?>
Run Code Online (Sandbox Code Playgroud)
首先,您的浏览器是否设置为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);
Run Code Online (Sandbox Code Playgroud)