如何从Facebook Post Insights获取JSON对象

时间:2016-03-08 03:14:38

标签: php json facebook

我试图从facebook帖子获得印象的价值:但我不能从JSON获得一个数字,当我想从json对象指定字段时我得到错误..

<?php echo $reach['values']['value']; ?> 这应该从洞察电话中返回 ..

当我从URL调用时,这是 JSON enter image description here

那么我试试这个:

<?php foreach ($post as $key): ?>
    <div class="postHolder">
        <h3><?php echo $key['message'] ?></h3>
        <p><?php echo $key['id'] ?></p>
    </div>
    <?php 
        try {
            $imp_request = $fb->get('/'.$key['id'].'/insights/post_impressions_unique?fields=values');
            $reach = $imp_request->getGraphEdge();
        } catch(Facebook\Exceptions\FacebookResponseException $e) {
            // When Graph returns an error
            echo 'Graph returned an error: ' . $e->getMessage();
            unset($_SESSION['facebook_access_token']);
            echo "<script>window.top.location.href='http://localhost/insights/'</script>";
            exit;
        } catch(Facebook\Exceptions\FacebookSDKException $e) {
        // When validation fails or other local issues
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

                    ?>
        <div class="insHolder">
            <?php echo $reach; ?>
        </div>

<?php endforeach; ?>

这会让我回头:

[{"values":[{"value":1}],"id":"{post_id}\/insights\/post_impressions_unique\/lifetime"}]

1 个答案:

答案 0 :(得分:0)

答案

我使用此代码获取最近的对象: [{'value'=1}]

  • <?php echo json_encode($reach[0]['values']); ?>

然后我使用基本 JS 调用删除所有字符什么不是 [0-9]

function reachText() {
    $('.reach').each(function(){
        reach = $(this).text().replace(/[^0-9]/g, '');
        $(this).text(reach);
    });
}