2017-10-20 111 views
-2

这是我的代码:$标题的Unicode转换阵列为UTF-8 PHP

<?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, 

    ])); 
} 

?> 

输出数据是:你\ u2019re活到老,在泥玩。 #tempixel摄影师@ samarthv.pattar在雨后的反射中抛出一个\ u270c \ ufe0f标志。

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

+1

据我所见,所有这些代码都与这个问题无关,实际上可以这样写:“我有一个类似于......的字符串......在他的反射中抛出一个\ u270c \ ufe0f符号......”并且需要将'\ u'转义转换为UTF-8。“ – IMSoP

+0

使用[mb_convert_encoding()](http://php.net/manual/en/function.mb-convert-encoding.php) – Jeff

+1

你是否手动拆分json-string?你为什么不只是'json_decode'呢? – Jeff

回答

2

这似乎有点但愚蠢的我。你不应该尝试自己解析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']); 
} 

Btw。有一个官方的Instagram Api,这应该是官方的方式来获得你想要的信息。 https://www.instagram.com/developer/endpoints/media/ 你目前的行为可能违反了他们的使用条款。

+0

它在$ json = $ m [1]中有错误; 错误:语法错误,意外';' – Mhdi

+0

在'{' – Philipp

+0

Unicode字符有坏习惯使得json_encode下降死亡之前在if条件中添加''''。这就是把我带到这里的原因。 –