How to retrieve CSV data from Google Sheets using PHP

I’m having trouble getting CSV data from a Google Sheets document through PHP. When I try to access the sheet, I keep getting a redirect error that says Moved Temporarily with a long authentication URL.

<?php
$sheet_url = 'https://docs.google.com/spreadsheets/d/1234567890abcdef/export?format=csv&gid=0';

$file_handle = fopen($sheet_url, 'r');
if ($file_handle !== FALSE) {
    while (($csv_data = fgetcsv($file_handle, 2000, ',')) !== FALSE) {
        $column_count = count($csv_data);
        for ($i = 0; $i < $column_count; $i++) {
            echo $csv_data[$i] . ' ';
        }
        echo '<br>';
    }
    fclose($file_handle);
} else {
    echo 'Cannot open the spreadsheet';
}
?>

The spreadsheet is set to public access and I got the sharing link from the Share menu. I think the issue might be related to using Google Workspace accounts instead of regular Gmail accounts. The same code works fine with personal Google accounts but fails with business accounts.

Has anyone dealt with this authentication problem before? Any suggestions on how to properly access Google Workspace spreadsheets?

That redirect is Google enforcing extra verification for Workspace domains. Hit the same wall six months ago migrating our reporting system. Workspace admins can set org-wide policies that require explicit permission even for public docs. I switched to file_get_contents() with a custom stream context - proper headers and cookie handling. Some Workspace setups will still block this completely though. If you’re in a corporate environment, you might have to use the Google Sheets API with service account credentials instead. More setup, but it bypasses all the domain restrictions. CSV export gets unreliable once enterprise policies kick in.

workspace accounts can be weird about this. add a user agent header to your request - google often blocks requests that don’t have proper headers. also try changing /edit#gid=0 to /export?format=csv&gid=0 in the sheet url. workspace handles urls differently than regular accounts.

Had this exact problem with corporate Google Workspace accounts last year. It’s not really an authentication issue - Workspace admins usually have stricter sharing policies that override your document permissions. Even if you set a sheet to ‘public,’ the org’s security settings can still force authentication. Try cURL instead of fopen since it handles redirects better. Set CURLOPT_FOLLOWLOCATION to true and CURLOPT_SSL_VERIFYPEER to false for testing. But honestly, you’ll probably need to ask your IT admin to adjust the workspace sharing settings or just switch to the Google Sheets API with proper OAuth. The API’s way more reliable for production anyway, even though it’s more work upfront.