doujiang2020 2017-06-22 07:43
浏览 26
已采纳

将数据附加到json文件php

I am using this php library to communicate with the spotify api to get my user details. The spotify api returns user data which I then want to add to a json file. Basically, whatever is sent back from the api I want to append to the json file for each user.

The data returned from the api looks like the following when I do print_r($api->me()); This is basically coming from this api call.

stdClass Object ( [display_name] => Paul Flanagan 
[email] => paulflanagan@gmail.com 
[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 )

I want to write this code to a json file

I have attempted many approaches but as I am more javascript focused than php I am struggling to write the data correctly. My latest attempt at the code looks like this:

<?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();

    }
?>
  • 写回答

1条回答 默认 最新

  • dongyo7931 2017-06-22 08:01
    关注

    As $api->me() returns object - you cannot write it to a file directly. You should convert object to a string. Simple way is to json_encode it:

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

    Next problem - is overwriting data. As you open file with w+ - you file gets truncated to 0 length.

    Solution here depends on what you need with previous data. If you want to rewrite some data - I think current behaviour does it already.

    If you want to append data to a file - you should use another mode when you open file, for example a+. But in this case, file contents won't be correct json, as you write to file not a single json string, but several strings, which is not correct json. So, it's up to you to find a proper solution.

    Update:

    According to file name, I suppose you store users in it. So, I think there's a list of users, encoded in json. So, a brief solution can be:

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)