2012-03-28 46 views
0

大家好我是PHP的新手,這是我第一次使用php的應用程序。如何訪問此數據?

我試圖通過圖形api創建一個新的相冊,並上傳照片到它。

我已經在下面的代碼,問題是當創建一個相冊後facebook圖形api返回的數據包含該相冊的ID和該ID後來用於上傳照片到該相冊。

在我的情況我得到的數據,但我無法通讀它,我試圖訪問它作爲一個對象,作爲一個數組,但沒有任何工作。

當我試圖打印它整個它是給這樣的輸出檢查的可行性。 Result: {"data":[{"id":"321215475937088","from":{"name":"Lorem …

我想知道如何訪問此id元素? $ result是一個數組,對象還是什麼。我嘗試了所有可能的方法,但我沒有得到所需的輸出結果。

// Create a new album 
     $graph_url = "https://graph.facebook.com/me/albums?" . "access_token=" . $access_token; 

     $postdata = http_build_query(array('name' => $album_name, 'message' => $album_description)); 
     $opts = array('http' => array('method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata)); 
     $context = stream_context_create($opts); 
     //$result = json_decode(file_get_contents($graph_url, false, $context)); 
     $ch = curl_init(); 
     $timeout = 5; 
     curl_setopt($ch, CURLOPT_URL, $graph_url); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
     $result = curl_exec($ch); 
     curl_close($ch); 
     echo "<pre>"; 
     echo "Result: " . $result; //output of this line is given above 
     echo "Result[id]: " . $result[id]; //Notice: Use of undefined constant id - assumed 'id' ... 
     echo "Result[data][id]: " . $result[data][id]; //Notice: Use of undefined constant data - assumed 'data'... 
//Notice: Use of undefined constant id - assumed 'id'... 
//Fatal error: Cannot use string offset as an array in ... 
     echo "Result ID: " . $result -> id; 
     echo "Data - >ID: " . $data->id; 
     echo "Data ID: " . $data[id]; 
     echo "</pre>"; 
     // Get the new album ID 
     $album_id = $result -> id; 
+2

您得到的數據是JSON。 – 2012-03-28 16:27:04

+0

可能'json_decode'在這種情況下很方便嗎? http://php.net/manual/en/function.json-decode.php – ianace 2012-03-28 16:30:47

回答

2

你得到JSON序列化對象。 您需要在使用前將其反序列化。 你可以做這樣的:

echo "Result: " . $result; 
$result = json_decode($result); 

之後,你可以訪問該對象的屬性:

echo "Result ID: " . $result->data[0]->id; 

*請注意,您的響應串數據是包含對象

1

Graph API的響應是JSON序列化的。

使用json_decode反序列化「時間

print_r(json_decode($result)); 

BTW,使用Facebook PHP SDK和節省自己的時間和代碼;)

1

其JSON格式。您可以使用json_decode()將其轉換爲數組/對象;

$json_data = json_decode($responce_string); 

閱讀手冊,瞭解更多信息

1
數組

使用json_decode來反序列化接收到的JSON字符串。