【问题标题】:JSON response with objects of the same name - Instagram comments具有同名对象的 JSON 响应 - Instagram 评论
【发布时间】:2016-01-07 22:45:22
【问题描述】:

我一直在构建一个测试应用程序,它从 Instagram 收集图片和某些用户信息(仅使用 PHP)。我没有使用官方 API,而是解析从 url 获得的 JSON 响应。

我正在尝试为某个帖子收集 cmets。问题是当有多个评论时,我可以看到每条评论的文本,但响应中的对象名称是相同的(每条评论都重复):{text}

这是一个简短的示例响应:

{"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

如您所见,对于每条评论,我都需要抓取一个“文本”对象。

这是我解析 JSON 并获取评论文本的函数(缩短):

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'];

}

我有另一个函数,通过简单地回显结果来显示 $the_pic_cmets。

echo $the_pic_comments;

如果有多个 {text} 对象,我将如何显示每条评论?我假设某种 foreach() 循环可能会起作用,但我无法让 foreach() 与我的 json_decode() 函数一起工作。

这目前有效,但只显示一条评论,其他所有内容都被忽略。

您能帮我创建一个从 JSON 响应中获取每条评论的循环吗?

谢谢!

【问题讨论】:

    标签: php json instagram


    【解决方案1】:

    单从你的代码来看,似乎应该是:

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

    请注意,由于您没有使用官方 API,如果 Instagram 更改其代码中的任何内容,您的机制可能随时中断,恕不另行通知。

    【讨论】:

    • 感谢您的反馈。我已经尝试了很多变体,它根本没有打印出任何东西。我不知道为什么我不能让它工作。我会继续玩它的。
    • 做 var_dump($insta_array);并找到实际的 cmets 数组在哪里。真的很简单!
    • 如你所说,非常简单。我没有在正确的地方运行循环。在你的帮助下搞定了。再次感谢!
    猜你喜欢
    • 2016-05-27
    • 2020-10-31
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多