大家好我是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;
答案 0 :(得分:2)
您正在获取JSON序列化对象。 您需要在使用前对其进行反序列化。 你可以这样做:
echo "Result: " . $result;
$result = json_decode($result);
之后,您可以访问该对象的属性:
echo "Result ID: " . $result->data[0]->id;
*请注意,响应字符串中的数据是包含对象的数组
答案 1 :(得分:1)
来自Graph API的响应是JSON序列化的。
使用json_decode
反序列化'em
print_r(json_decode($result));
BTW,使用Facebook PHP SDK并节省时间和代码;)
答案 2 :(得分:1)
答案 3 :(得分:1)
对响应使用json_decode
以反序列化收到的JSON字符串。