2017-06-22 135 views
0

我正在使用this php library與spotify api進行通信以獲取我的用戶詳細信息。 spotify api返回用戶數據,然後我想添加到json文件中。基本上,無論是從api發回我想附加到每個用戶的json文件。將數據附加到json文件php

當我做這些時,從api返回的數據如下所示print_r($api->me());這基本上來自這個api call

stdClass Object ([display_name] => Paul Flanagan 
[email] => [email protected] 
[external_urls] => stdClass Object ( 
[spotify] => https://open.spotify.com/user/21aydctlhgjst3z7saj2rb4pq) [followers] => stdClass Object ( 
[href] => [total] => 19) 
[href] => https://api.spotify.com/v1/users/2391231jasdasd1 
[id] => 21aydctlhgjst3z7saj2rb4pq 
[images] => Array ([0] => stdClass Object ( 
[height] => [url] => https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/18301863_452622995075637_5517698155320169855_n.jpg?oh=9e949fafd3ee84705ea5c1fa1aa9c811&oe=59C9F63C 
[width] =>)) [type] => user [uri] => spotify:user:21aydctlhgjst3z7saj2rb4pq) 

我想這個代碼寫我曾嘗試多種方法JSON文件

但我更關注的JavaScript比PHP我很努力正確地寫入數據。我在代碼最新嘗試是這樣的:

<?php 

    require 'vendor/autoload.php'; 

    $session = new SpotifyWebAPI\Session(
     'KEY1', 
     'KEY2', 
     'CALLBACK_URL' 
    ); 

    $api = new SpotifyWebAPI\SpotifyWebAPI(); 

    if (isset($_GET['code'])) { 
     $session->requestAccessToken($_GET['code']); 
     $api->setAccessToken($session->getAccessToken()); 

     $file = "users.json"; 
     $json = json_decode(file_get_contents($file), true); 
     $file = fopen($file,'w+'); 
     fwrite($file, $api->me()); 
     fclose($file); 

     print_r($api->me()); 
    } else { 
    $options = [ 
     'scope' => [ 
      'user-read-email', 
     ], 
    ]; 

    header('Location: ' . $session->getAuthorizeUrl($options)$ 
    die(); 

    } 
?> 
+0

'$ api-> me()'返回什麼? –

+0

hey @u_mulder見上文。它是第一個片段 - 看起來像這個'stdClass對象([display_name] => Paul Flanagan ...' –

+0

那麼當你將它寫入文件時會發生什麼? –

回答

1

由於$api->me()回報object - 你不能直接將其寫入文件。您應該將對象轉換爲string。簡單的方法是json_encode它:

$file = "users.json"; 
$json = json_decode(file_get_contents($file), true); 
$file = fopen($file,'w+'); 
fwrite($file, json_encode($api->me())); 
fclose($file); 

下一個問題 - 覆蓋數據。當你用w+打開文件 - 你的文件被截斷爲0的長度。

這裏的解決方案取決於您以前需要的數據。如果你想重寫一些數據 - 我認爲目前的行爲已經做到了。

如果要將數據附加到文件 - 打開文件時應使用another mode,例如a+。但在這種情況下,文件內容將不正確json,因爲你寫入文件不是一個單一的json字符串,而是幾個字符串,這是而不是正確的json。所以,這取決於你找到一個合適的解決方案。

更新:

根據文件名,我想你存儲用戶的。所以,我認爲有一個用json編碼的用戶列表。所以,一個簡單的解決方案可以是:

$file = "users.json"; 
$json = json_decode(file_get_contents($file), true); 

// Now $json stores list of you current users. I suppose it's a simple array of arrays 

// This is data for a new user 
$new_user = $api->me(); 

// as data `$new_user` is object, I think you need to convert it to array 
// this can be done as: 
$new_user = json_decode(json_encode($new_user), true); 

// now, add new user to existsing array 
$json[] = $new_user; 

$file = fopen($file,'w+'); 

// now we can encode `$json` back and write it to a file 
fwrite($file, json_encode($json)); 
fclose($file); 
+0

如果你有一個列表,添加一個關於可能的解決方案的小更新的用戶在文件中。 –