Search code examples
phpcloudinarysmartsheet-api

How can I get a smartsheet as excel file and put it to cloudinary in PHP?


I need your help to get a smartsheet as excel and put it to cloudinary in PHP. I use the code bellow.

/**
 * @param $sheetId
 */
public function getSheetAsExcel($sheetId)
{
    $url = self::SMART_SHEET_BASE_URL . '/sheets/' . $sheetId;
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

    $headers = array();
    $headers[] = 'Authorization: Bearer ' . $this->smartsheetCredentials;
    $headers[] = 'Accept: application/vnd.ms-excel';

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        echo 'Error:' . curl_error($ch);
    }
    curl_close($ch);

    return $result;
}

A file is created in cloudinary but when I donwload it, I have a wrong format.

screenshot of the message shown

$outStream = $this->smartsheetClient->getSheetAsExcel($smart_sheet_id);
$file_name = 'filename.xlsx';
$cloudinarySignature = (new CloudinayClient())->getCloudinarySignature();

$temp = tmpfile();
$path = stream_get_meta_data($temp)['uri'];
fwrite($temp, file_put_contents($path, $outStream));
fseek($temp, 0);

$cloudinaryResponse = \Cloudinary\Uploader::upload($path, [
    "public_id" =>  $file_name,
    "resource_type" => "auto",
    "signature" => $cloudinarySignature,
    "version" => time()
]);

fclose($temp);


Solution

  • I updated my code with following. The problem was probably the tmpfile().

    $file = $this->smartsheetClient->getSheetAsExcel($smart_sheet_id);
    $file_name = 'filename.xlsx';
    $cloudinarySignature = (new CloudinayClient())->getCloudinarySignature();
    
    $path = self::TMP_FOLDER ."/$file_name";
    file_put_contents($path, $file);
    
    $cloudinaryResponse = \Cloudinary\Uploader::upload($path, [
        "public_id" =>  $file_name,
        "resource_type" => "auto",
        "signature" => $cloudinarySignature,
        "version" => time()
    ]);
    
    unlink($path);