douzhang6176 2016-01-07 22:45
浏览 50
已采纳

JSON响应与同名对象 - Instagram评论

I have been building a test app that gathers pictures and certain pieces of user information from Instagram (only using PHP). I am not using the official API, but instead parsing the JSON response that I get from the url.

I'm trying to gather comments for a certain post. The issue is that when there's more than one comment, I can see the text for each comment, but the object name in the response is the same (it repeats for every comment): {text}.

Here's an abbreviated example response:

{"text":"I think this is funded by my company","created_at"...,"user":{"username"...}, blah blah blah},

{"text":"Very cool","created_at"...,"user":{"username"...blah blah blah

As you can see, for each comment made, there is a "text" object that I need to grab.

Here is my function (shortened) that parses the JSON and gets the comment text:

function scrape_insta_user_post($postid) {

  $insta_source = file_get_contents('https://www.instagram.com/p/'.$postid.'/');
  $shards = explode('window._sharedData = ', $insta_source);
  $insta_json = explode(';</script>', $shards[1]); 
  $insta_array = json_decode($insta_json[0], TRUE);

  global $the_pic_comments;

  $the_pic_comments = $insta_array['entry_data']['PostPage'][0]['media']['comments']['nodes'][0]['text'];

}

I have another function that I use to display $the_pic_comments by simply echoing the results.

echo $the_pic_comments;

In cases where there is more than one {text} object, how would I go about displaying each comment? I'm assuming some kind of foreach() loop might work, but I can't get the foreach() to work with my json_decode() function.

This currently works, but only displays one comment, and everything else is ignored.

Can you help me create a loop that will get each comment from the JSON response?

Thanks!

  • 写回答

1条回答 默认 最新

  • dongyejun1983 2016-01-07 23:11
    关注

    Judging from your code alone, it seems that it should be:

    foreach ($insta_array['entry_data']['PostPage'][0]['media']['comments']['nodes'] as $comment) {
        echo $comment['text']; // Or add to array, eg. $comments[] = $comment['text'];
    }
    

    Note that since you are not using official API, your mechanism may break any time without notice shall Instagram change anything in their code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值