You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Facebook推送的JSON数据中获取media_id值?

How to extract "media_id" from Facebook/Instagram webhook JSON data in PHP?

我看了你的代码和收到的JSON数据,问题出在你没有正确处理JSON里的数组结构,还有PHP数组键名的引号使用上。

你的原始代码问题点:

  1. $data[entry][changes][value][media_id] 里的键名没有加引号,PHP会把entry、changes这些当成常量解析,这会导致警告甚至错误(如果这些常量未定义的话)。
  2. JSON里的entry和changes都是数组类型(用[]包裹),你需要先访问数组的第一个元素(索引0),才能拿到里面的对象。

修正后的代码:

<?php 
$challenge = $_REQUEST['hub_challenge']; 
$verify_token = $_REQUEST['hub_verify_token']; 
// Set this Verify Token Value on my Facebook App 
if ($verify_token === 'token') { 
    echo $challenge; 
    $readjson = file_get_contents('php://input'); 
    // Decode JSON into associative array
    $data = json_decode($readjson, true); 

    // 先检查数组层级是否存在,避免报错
    if (isset($data['entry'][0]['changes'][0]['value']['media_id'])) {
        $media_id = $data['entry'][0]['changes'][0]['value']['media_id'];
        print_r($media_id); // 输出media_id值
    }

    // Response code 200 - ok 
    header('HTTP/1.0 200 OK'); 
} else { 
    header('HTTP/1.0 401 Unauthorized'); 
} 
?>

为什么这样能行?

我们来对应你的JSON结构拆解:

  • $data['entry'] 对应JSON里的entry数组,取第一个元素[0]拿到包含changes的对象;
  • ['changes'][0] 对应changes数组里的第一个变化项;
  • 最后通过['value']['media_id']就能精准获取到你要的media_id值。

另外,加上isset()判断是为了防止webhook发送的JSON结构有变动时,不会因为数组索引不存在而抛出致命错误,让代码更健壮。

你收到的JSON数据参考:

{ 
    "object": "instagram", 
    "entry": [{ 
        "id": "0", 
        "time": 1573295665, 
        "changes": [{ 
            "field": "story_insights", 
            "value": { 
                "media_id": "17887498072083520", 
                "impressions": 444, 
                "reach": 44, 
                "taps_forward": 4, 
                "taps_back": 3, 
                "exits": 3, 
                "replies": 0 
            } 
        }] 
    }] 
}

内容的提问来源于stack exchange,提问作者Vincy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:30:52