【问题标题】:Convert unicode array to UTF-8 php [duplicate]将unicode数组转换为UTF-8 php [重复]
【发布时间】:2018-04-01 09:16:39
【问题描述】:

这是我的代码:

<?php
$url = 'https://www.instagram.com/p/BachWpLgFAp/';
$content = file_get_contents($url);
$first_step = explode( 'edge_media_to_caption": {"edges": [{"node": {"text": "' , $content );
$second_step = explode("}}]}" , $first_step[1] );

$str = $second_step[0];
$str2 = substr($str, 0, -1);
print_r ($str2);

$caption = $str2;
if($user_message == "/test"){

            var_dump(bot('sendMessage',[
        'chat_id'=>$chat_id,
        'text'=>$caption,

    ]));
}

?>

$caption 的输出数据是: 你永远不会老到不能玩泥巴。 #teampixel 摄影师 @samarthv.pattar 在雨后向他的倒影投掷 \u270c\ufe0f 标志。

如何将 \u 代码转换为 utf-8?

【问题讨论】:

  • 据我所知,所有这些代码都与问题无关,实际上可以表述为“我有一个类似...throws a \u270c\ufe0f sign at his reflection... 的字符串,需要将\u 转义转换为UTF-8。”
  • 您是手动拆分 json 字符串吗?你为什么不直接json_decode呢??
  • @Gajanan Kulkarni 。我的代码给出了 Instagram 帖子的标题,但是输出中的字符是 unicode,我想要 utf-8
  • @Jeff 在哪里使用?当我使用 json_decode($str2);没有输出。

标签: php arrays unicode utf-8 telegram-bot


【解决方案1】:

这对我来说似乎有点愚蠢。您不应该尝试自己解析 json 字符串。为什么不直接提取整个 json 字符串然后使用json_decode

$url = 'https://www.instagram.com/p/BachWpLgFAp/';
$content = file_get_contents($url);
if (preg_match('/<script[^>]+>\s*window\._sharedData[^\{]+(\{.*?);\s*<\/script>/ms', $content, $m)) {
    $json = $m[1];
    $jsonData = json_decode($json, true);
}

得到jsonData后,可以在给定的数组中搜索edge_media_to_caption。

foreach ($jsonData['entry_data']['PostPage'] as $page) {
    $graphql = $page['graphql'];
    var_dump($graphql['shortcode_media']['edge_media_to_caption']);
}

顺便说一句。有一个官方的 Instagram Api,它应该是获取所需信息的官方方式。 https://www.instagram.com/developer/endpoints/media/ 您当前所做的可能违反了他们的使用条款。

【讨论】:

  • $json = $m[1] 有错误;错误:语法错误,意外';'
  • {之前的if条件中添加)
  • Unicode 字符有让 json_encode 死掉的坏习惯。这就是把我带到这里的原因。
猜你喜欢
  • 2014-08-15
  • 2011-06-05
  • 2013-01-25
  • 2020-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 2021-07-06
相关资源
最近更新 更多