php curl japanese输出乱码

时间:2016-03-15 18:54:26

标签: php curl character-encoding

考虑以下网址: click here

日语字符有一些编码。我的电脑上的Firefox浏览器能够自动检测并显示字符。另一方面,对于Chrome,我必须手动将编码更改为“Shift_JIS”才能看到日文字符。

如果我尝试通过PHP-cURL访问内容,则编码文本会出现像这样的乱码

  

φîƂȂI݂ȂN`R〜TCgiAb gRXjɂ܂我

我试过了:

  curl_setopt($ch, CURLOPT_ENCODING, 'Shift_JIS');

我也尝试过(下载卷曲响应后):

  $output_str = mb_convert_encoding($curl_response, 'Shift_JIS', 'auto');
  $output_str = mb_convert_encoding($curl_response, 'SJIS', 'auto');

但这也不起作用。

这是完整的代码

   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language: en-US,en;q=0.5',
        'Connection: keep-alive'
    ));

    //curl_setopt($ch, CURLOPT_ENCODING, 'SJIS');
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);

2 个答案:

答案 0 :(得分:6)

该页面没有返回有效的HTML,它实际上是Javascript。如果您使用curl获取并输出它,请将header('Content-type: text/html; charset=shift_jis');添加到您的代码中,当您在Chrome中加载时,字符将正确显示。

由于HTML没有指定字符集,您可以使用header()从服务器指定它。

要实际转换编码以便在终端中正确显示,您可以尝试以下操作:

使用iconv()转换为UTF-8

$curl_response = iconv('shift-jis', 'utf-8', $curl_response);

使用mb_convert_encoding()转换为UTF-8

$curl_response = mb_convert_encoding($curl_response, 'utf-8', 'shift-jis');

这两种方法对我有用,我能够在终端上看到日文字符显示正确。

UTF-8应该没问题,但是如果你知道你的系统使用了不同的东西,你可以试试。

希望有所帮助。

答案 1 :(得分:0)

以下代码将在浏览器中正确输出日文字符: -

<?php

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $setUrlHere);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

// grab URL content
$response = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

header('Content-type: text/html; charset=shift_jis');
echo $response;
相关问题