Direct download link from Google Apps for Business

By parsing out the Google document id from a sharing link in Drive or Apps for business, you can download files directly without being presented with a web interface. Here’s how…

Taking an original link with the syntax:

https://drive.google.com/a/yourgooglebusinessname.com/file/d/0B271wWuAZ0NwVHpPbVkwR3lLb1k

We need to parse it to pull out just the id ‘0B271wWuAZ0NwVHpPbVkwR3lLb1k’, and create a new link in this form:

https://docs.google.com/uc?export=download&id=0B271wWuAZ0NwVHpPbVkwR3lLb1k

In PHP, if we’ve got the original link url from (say) the Salesforce PHP toolkit in $googledoc->Url, the code might look like this:

try {
	$googledoc_id = substr($googledoc->Url, strrpos($googledoc->Url, '/',-2)+1, strpos($googledoc->Url, '?')- strrpos($googledoc->Url, '/',-2)-1);
	echo '<a href="https://docs.google.com/uc?export=download&id='.$googledoc_id.'" class="Attachment">link</a>';					
} catch (Exception $e) {
	echo '<!-- googledoc id extraction - Caught exception: '.$e->getMessage().'-->';
	echo '<a href="'.$googledoc->Url.'" class="Attachment">link</a>';											    
}