phpexcelcurlsmartsheet-apismartsheet-api-1.1

Save smartsheet as .xls on server (curl / php)


i want to save a smartsheet to my server (as .xls). But i always get an .xls filled with json-code. I get the "file_put error" if i use json_decode(..) and the .xls is completely empty. If i do it via curl on my desktop i get the right .xls filled with everything i need.

$baseURL = "https://api.smartsheet.com/1.1";
$headers = array("Authorization: Bearer ".$inputToken);
.
.
array_push($headers,'"Accept: application/vnd.ms-excel" -o  tmpfile.xls --insecure');
$curlSession = curl_init($sheetDetail_url);
curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
$smartsheetData = curl_exec($curlSession);

if (curl_errno($curlSession))
{
    echo "Oh No! Error: " . curl_error($curlSession);
}else{
    // Assign response to PHP object
    $sheetsObj = json_decode($smartsheetData);
    // close curlSession
    curl_close($curlSession);
}
$file1="tmpfile.xls";
if(!(file_put_contents($file1, $sheetsObj))){
    echo "file_put error";
} 

I hope you can help me. Thanks


Solution

  • The items that need adjusted in your example are the headers and how the response is handled.

    First, using curl command line options in the headers will not work. Instead you just need to specify that an XLS file should be returned with headers like the following:

    $headers = array("Authorization: Bearer ".$inputToken,
        "Accept: application/vnd.ms-excel");
    

    Second, since an XLS file is going to be returned we will not want to parse that response as JSON. Instead, immediately write the response out to a file.

    With that in mind the following example should work for you and retrieved the specified sheet as an XLS file. Make sure to replace YOUR_TOKEN and YOUR_SHEET_ID with the appropriate values.

    <?php
    $inputToken = 'YOUR_TOKEN';
    $baseURL = "https://api.smartsheet.com/1.1";
    
    $sheetDetail_url = $baseURL.'/sheet/YOUR_SHEET_ID';
    
    $headers = array("Authorization: Bearer ".$inputToken,
        "Accept: application/vnd.ms-excel");
    
    $curlSession = curl_init($sheetDetail_url);
    curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curlSession, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, TRUE);
    
    $smartsheetData = curl_exec($curlSession);
    
    // Check for error or save the file
    if (curl_errno($curlSession))
    {
        echo "Oh No! Error: " . curl_error($curlSession);
    }else{
        curl_close($curlSession);
    
        $file1="tmpfile.xls";
        if(!(file_put_contents($file1, $smartsheetData))){
            echo "file_put error";
        }
    }
    
    ?>