2013-02-12 47 views
0

我在Facebook中提供訪問令牌後,使用Facebook打開圖作爲json提要格式來獲取頁面名稱。無法使用json_decode讀取json提要

這裏是我的代碼:

$get_pages = file_get_contents("https://graph.facebook.com/me/accounts?access_token=".$_POST['access_token']); 
$get_pages = json_decode($get_pages); 

foreach($get_pages->data as $page){ 
    echo $page[name]; 
    } 

我想呼應的頁面的名稱。 JSON的代碼,Facebook的提供這個樣子的:

{ 
     "data": [ 
      { 
      "category": "website", 
      "name": "jjj", 
      "access_token": "jjj", 
      "id": "jjj", 
      "perms": [ 
       "jjj", 
       "jjj", 
       "jjj", 
       "jjj", 
       "jjj", 
       "jjj" 
      ] 
      }, 
      { 
      "category": "Community", 
      "name": "ggg", 
      "access_token": "ggg", 
      "id": "ggg", 
      "perms": [ 
       "ggg", 
       "ggg", 
       "ggg", 
       "ggg", 
       "ggg", 
       "ggg" 
      ] 
      } 
], 
    "paging": { 
     "next": "hhh" 
    } 
} 

我收到此錯誤:

catchable fatal error: object of class stdclass could not be converted to string in 
with this line of code :$get_pages = json_decode($get_pages); 

我究竟做錯了什麼?

+2

你混合數組和對象訪問。對於條目,使用'json_decode($ data,TRUE)'在foreach和'[「name」]'中獲得'[「page」]'的全數組結果。否則使用' - >名稱'。另見http://array.include-once.org/ – mario 2013-02-12 22:00:18

+0

你確定這是正確的行號嗎?我已經用您的數據測試過它,並且沒有任何錯誤。 (不能真的相信錯誤是在那一行) – hek2mgl 2013-02-12 22:07:56

+0

我解決了我的問題。請參閱下面的答案。 – 2013-02-12 22:23:52

回答

0

我解決它:)我改變了我的代碼如下:

$get_pages = file_get_contents("https://graph.facebook.com/me/accounts?access_token=".$_POST['access_token']); 
$get_pages = json_decode($get_pages, TRUE); 
echo '<select id="select_page">'; 
foreach($get_pages[data] as $page_name){ 
echo '<option>'.$page_name[name].'</option>'; 
} 
echo '</select>';