如何使用curl访问更深层次的json树?

时间:2011-06-24 06:44:07

标签: php json facebook curl

我正在尝试学习如何使用CURL和Json访问从Facebook图形api发送的数据。

我正在使用以下函数来提取帖子数据:

 function loadFB($fbID){
      $url="https://graph.facebook.com/".$fbID."/feed?limit=1&access_token=xxxx";
      $c = curl_init($url);
      curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
      $page = json_decode(curl_exec($c));
      curl_close($c);
      $post=reset($page->data);

      if($post->message == '') {

        $post_msg = '<a href="' . $post->link . '">' . $post->name . '</a>';

      } else {

        $post_msg = $post->message;

      }

      return $post_msg;
 }

示例JSOn数据如下所示:

{
"data": [
  {
     "id": "xxxx",
     "from": {
        "name": "xxx",
        "category": "xxx",
        "id": "xxx"
     },
     "picture": "xxxxxxxxx",
     "link": "xxxxxxx",
     "name": "Event name goes here",
     "properties": [

        {
           "text": "Friday, July 15, 2011 at 4:00pm"
        },
        {
           "text": "Venue Name"
        }
     ],
     "icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yW/r/r28KD-9uEMh.gif",
     "type": "link",
     "object_id": "xxx",
     "created_time": "2011-06-23T06:46:17+0000",
     "updated_time": "2011-06-23T06:46:17+0000",
     "likes": {
        "data": [
           {
              "name": "xxxx",
              "category": "xxx",
              "id": "xxxx"
           }
        ],
        "count": 1
     }
  }
],
"paging": {
  "previous": "xxxxx",
  "next": "xxx"
}
 }

目前,我可以检索页面更新的消息,或者如果它是一个事件,我可以检索事件名称和事件的链接。

但是,如果我想要检索说事件日期或地点名称怎么办?它属于另一层“财产”。

到目前为止,使用我的代码,我可以使用$ post-&gt;消息访问第一级别的内容,但是当我尝试$ post-&gt; properties-&gt;文本时这不起作用 - 所以我不这样做了解这是如何工作的。最重要的是,在“属性”中,有2个“文本”,这增加了我对如何访问这些内容的困惑。

任何指针?

2 个答案:

答案 0 :(得分:2)

$post->properties是一个数组:

$post->properties[0]->text;

答案 1 :(得分:0)

上述数据中的属性是一个INDEXED ARRAY,因此您需要$post->properties[x].text其中x对于第一个项目为0,对于第二个项目为1,等等...