使用iconv()和mb_strtolower()

时间:2016-08-02 17:20:26

标签: php json twitter encoding

编码对我来说是地狱。我一定很傻。

我正在从twitter中提取主题标签以制作我自己的书签库。

$url = 'https://api.twitter.com/1.1/statuses/mentions_timeline.json';
$requestMethod = 'GET';
$getfield = '?count=200&include_rts=1&max_id=397109847755210753';
$twitterGET = new TwitterAPIExchange($settingsGET);
$twitterPOST = new TwitterAPIExchange($settingsPOST);
$jsonString = $twitterGET->setGetfield($getfield)
         ->buildOauth($url, $requestMethod)
         ->performRequest();
$json_arr = json_decode($jsonString, true);

由于许多twits是西班牙语,因此它们具有á

等字符

我读过的Twitter应该在UTF-8中进行编码,但是当我将主题标签字符串转换为小写字母时,我会获得unicode内容。请参阅以下代码:

foreach ($json_arr as $mytwit) {
    $twitText=$mytwit["text"];
    $twitHashTags=$mytwit["entities"]["hashtags"];
    foreach($twitHashTags as $tag){
        $tag=mb_strtolower($tag, 'UTF-8');
        $twitKeyWords[]=$tag;
        echo $tag;
    }
    #==>outputs: tecnolog\u00edas
 }

接下来我尝试猜测那里有什么编码,我尝试使用这个可爱星球上所有可能编码的代码(下面只是很多尝试中的一个):

foreach($twitHashTags as $tag){
    $tag = iconv("ISO-8859-1", "UTF-8//IGNORE", $tag);
    $tag=mb_strtolower($tag, 'UTF-8');
    $twitKeyWords[]=$tag;
    echo $tag;
}
==>outputs: tecnolog\u00e3\u00adas (even worse, thanks)

我有2个问题。

  1. 如果在概念上不可能猜测字符串的编码,为什么twitter没有在某些字段中指定twit的编码,例如$twit["entities"]["bloody_encoding"]

  2. 有没有人对傻瓜有一个php-twitter编码建议?

  3. 哦,我也试过这个神奇的伎俩,但不幸的是不行: How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

1 个答案:

答案 0 :(得分:1)

我认为这是因为Twitter没有向您发送UTF-8编码数据,它使用unicode转义序列发送ASCII编码(或类似)

https://twittercommunity.com/t/is-it-normal-to-have-u-escaped-unicode-text-in-text-field-of-json-response-or-you-actually-retrieves-utf-8-code/13047

您能否详细介绍一下您正在做的事情,例如您正在进行的API调用以及您是否正在使用现有的Twitter客户端或SDK,或者您是否已推出你自己的