php save json to csv

Hello i'm working on a small project that i have to retrieve movies data from a json API, then save the result into a csv.
i'm able to display data with php eco but when i'm trying to write csv file i get the following
Warning: array_keys() expects parameter 1 to be array, object given on line 8
Warning: fputcsv() expects parameter 2 to be array, null given on line 9
Warning: array_flip() expects parameter 1 to be array, null given on line 10
Warning: array_merge(): Argument #1 is not an array on line 11
Warning: fputcsv() expects parameter 2 to be array, null given 11

$toplink = "https://api.themoviedb.org/3/movie/top_rated?api_key=3356bddf22b611f259916342a1a3ed50"
$toprated = file_get_contents($toplink);
   $toprated = json_decode($toprated);
   $top = $toprated->results;
    $header = false;
    foreach ($top as $row){
        if (empty($header)){
            $header = array_keys($row);
            fputcsv($fp, $header);
            $header = array_flip($header);
          }
        fputcsv($fp, array_merge($header, $row));
    }
    fclose($fp);
 ?>