JSON 回复同名对象 - Instagram 评论
JSON response with objects of the same name - Instagram comments
我一直在构建一个测试应用程序,从 Instagram 收集图片和某些用户信息(仅使用 PHP)。我没有使用官方 API,而是解析我从 url.
获得的 JSON 响应
我正在尝试为某个 post 收集 评论 。问题是,当有多个评论时,我可以看到每条评论的文本,但响应中的对象名称是相同的(每条评论重复):{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
如您所见,对于每条评论,我都需要抓取一个 "text" 对象。
这是我的函数(已缩短),它解析 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_comments。
echo $the_pic_comments;
如果有多个 {text} 对象,我将如何显示每条评论?我假设某种 foreach() 循环可能有效,但我无法让 foreach() 与我的 json_decode() 函数一起工作。
这目前有效,但只显示一条评论,其他所有内容都将被忽略。
你能帮我创建一个循环,从 JSON 回复中获取每条评论吗?
谢谢!
单从你的代码来看,好像应该是:
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 更改其代码中的任何内容,您的机制可能会随时中断,恕不另行通知。
我一直在构建一个测试应用程序,从 Instagram 收集图片和某些用户信息(仅使用 PHP)。我没有使用官方 API,而是解析我从 url.
获得的 JSON 响应我正在尝试为某个 post 收集 评论 。问题是,当有多个评论时,我可以看到每条评论的文本,但响应中的对象名称是相同的(每条评论重复):{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
如您所见,对于每条评论,我都需要抓取一个 "text" 对象。
这是我的函数(已缩短),它解析 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_comments。
echo $the_pic_comments;
如果有多个 {text} 对象,我将如何显示每条评论?我假设某种 foreach() 循环可能有效,但我无法让 foreach() 与我的 json_decode() 函数一起工作。
这目前有效,但只显示一条评论,其他所有内容都将被忽略。
你能帮我创建一个循环,从 JSON 回复中获取每条评论吗?
谢谢!
单从你的代码来看,好像应该是:
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 更改其代码中的任何内容,您的机制可能会随时中断,恕不另行通知。