【发布时间】: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 响应中获取每条评论的循环吗?
谢谢!
【问题讨论】: