I need to create spreadsheet using google drive PHP API, how can i do that ?
i already have code put it always get untitled file and when i click on it there is no data here is my code:
/**
* Insert new file.
*
* #param apiDriveService $service Drive API service instance.
* #param string $title Title of the file to insert, including the extension.
* #param string $description Description of the file to insert.
* #param string $parentId Parent folder's ID.
* #param string $mimeType MIME type of the file to insert.
* #param string $filename Filename of the file to insert.
* #return DriveFile The file that was inserted. NULL is returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $data) {
$file = new DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parentsCollectionData = new DriveFileParentsCollection();
$parentsCollectionData->setId($parentId);
$file->setParentsCollection(array($parentsCollectionData));
}
try {
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
print_r($createdFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
if(isset($_POST['insertFile'])){
$service = new apiDriveService($client);
insertFile($service,'Google Maps Mrakers.txt','ADD Google Map Mrakers To File',NULL,'text/plain',$_POST['data']);
exit;
}
You are having this issue because you are using an out-of-date version of the PHP client library. Please sync your client to the trunk of the project repository.
You would have to re-write some of your code as the client library has been refactored since you first wrote your code. The reference guides in the Google Drive SDK documentation have been updated to reflect this refactoring.
To create a Google Spreadsheet, insert a file without content with its mimeType set to application/vnd.google-apps.spreadsheet.
Related
I am using mpdf library to convert HTML to PDF and successfully stored my pdf file on local as well as remote server. But I don't want to store my pdf files on my code repos on server and like to utilize storage bucket available on google cloud.
/*
*/
private function generatePDF($params, $quotationId) {
$location = '/var/www/html/development/pdfs/';
$html = $this->load->view('quotation', $data, TRUE);
$filename = "quo_" .time() . ".pdf";
$mpdf = new \Mpdf\Mpdf(['mode' => 'en-IN', 'format' => 'A4']);
$mpdf->WriteHTML($html);
$mpdf->SetHTMLFooter('<p style="text-align: center; text-size: 12px;">This is computer generated quotation. It does not require signature.</p>');
$pdf = $mpdf->Output($location . $filename, 'F');
$this->UploadModel->upload($pdf, $filename);
}
public function upload($pdf, $pdfName) {
$storage = new StorageClient();
$bucket = $storage->bucket("bucketname");
$object = $bucket->upload($pdf, ['name' => $pdfName]);
$object = $bucket->object($pdfName);
$object->update(['acl' => []], ['predefinedAcl' => 'PUBLICREAD']);
}
Here I have used 'F' type in which it saves the pdf file in pdfs folder created in my code repo hosted on cloud server but I would like to directly store it to Google cloud storage bucket.
I am not having much experience about google cloud and mpdf library so looking for help and guidance to achieve the functionality.
Please kindly help me.
I see you are using Cloud Storage Client Libraries for PHP.
First, you need to install it to your machine:
composer require google/cloud-storage
And then you need to set up authentication by following the guide.
Once these are set create a bucket to store the PDFs.
Then replace your upload function with the code from the documentation:
use Google\Cloud\Storage\StorageClient;
/**
* Upload a file.
*
* #param string $bucketName the name of your Google Cloud bucket.
* #param string $objectName the name of the object.
* #param string $source the path to the file to upload.
*
* #return Psr\Http\Message\StreamInterface
*/
function upload_object($bucketName, $objectName, $source)
{
$storage = new StorageClient();
$file = fopen($source, 'r');
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload($file, [
'name' => $objectName
]);
printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}
i also faced same issue & came out with this solution, i hope it will help you.
use 'S' instead of 'F'parameter, so it will return string data & pass this data directly into upload method.
I know how do upload an object to Aws S3 Bucket like this:
try {
$oClientAws->putObject(array(
'Bucket' => 'bucket_test',
'Key' => 'fileName.jpg',
'Body' => fopen('path/to/file/fileName.jpg', 'r'),
'ACL' => 'public-read',
));
}
catch (Aws\Exception\S3Exception $e) {}
But i don't know how to download an object i can use $oClientAws->getObject(parms...) and change the content type of the header but this just show my file on the browser, but don't download the file.
tks!
File can be downloaded from s3 bucket using getObject method of s3client API
/**
* Gets file stored in Amazon s3 bucket.
*
* #param string $awsAccesskey , access key used to access the Amazon bucket.
* #param string $awsSecretKey , secret access key used to access the Amazon bucket.
* #param string $bucketName , bucket name from which the file is to be accessed.
* #param string $file_to_fetch , name of the file to be fetched, if the file is with in a folder it should also include the folder name.
* #param string $path_to_save , path where the file received should be saved.
* #return boolean true if the file is successfully received and saved else returns false.
*/
function get_from_s3_bucket( $awsAccesskey, $awsSecretKey, $bucketName, $file_to_fetch, $path_to_save ) {
try {
$bucket = $bucketName;
require_once('S3.php');
$s3 = new S3( $awsAccesskey, $awsSecretKey );
$object = $s3->getObject( $bucket, $file_to_fetch, $path_to_save );
if ( $object->code == 200 ) {
return true;
} else {
return false;
}
} catch ( Exception $e ) {
return false;
}
}
Refer the below link for more guidance:
http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html
Using the S3 standalone class (which I have found isn't much different from the AWS SDK) getObject has a saveTo param where you pass a filename to save the file to... Check out the method:
/**
* Get an object
*
* #param string $bucket Bucket name
* #param string $uri Object URI
* #param mixed $saveTo Filename or resource to write to
* #return mixed
*/
public static function getObject($bucket, $uri, $saveTo = false)
{
$rest = new S3Request('GET', $bucket, $uri, self::$endpoint);
if ($saveTo !== false)
{
if (is_resource($saveTo))
$rest->fp =& $saveTo;
else
if (($rest->fp = #fopen($saveTo, 'wb')) !== false)
$rest->file = realpath($saveTo);
else
$rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
}
if ($rest->response->error === false) $rest->getResponse();
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false)
{
self::__triggerError(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->response;
}
Here's a link to obtain the class: https://aws.amazon.com/code/1448
Hope this helps.
I am creating a txt/html file in google drive as document using the google drive sdk. the code creates successfully the document.
My question is that it is possible that it can also set the file permission as read-only file?
this is my code in creating the document,
$mkFile = $this->_service->files->insert($file, array('data' => $subcontent, 'mimeType' => 'text/html', 'convert' => true));
You can create Permission to Anyone only reader.
Code based from documentation Google Drive API V3:
https://developers.google.com/drive/api/v3/reference/permissions/create
public function permissionAnyone($fileId) {
$permissions = new Google_Service_Drive_Permission(array(
'role' => 'reader',
'type' => 'anyone',
));
try {
$result = $this->service_drive->permissions->create($fileId, $permissions);
} catch (Exception $e) {
$result = $e->getMessage();
}
return $result;
}
you can use permissions.patch to update the permissions for a file after it has been inserted. There is currently a bug in the API that doesn't allow you to set the permissions at the time you insert the file. You have to patch them after the file has been placed on drive.
Code ripped from documentation link above.
/**
* Patch a permission's role.
*
* #param Google_Service_Drive $service Drive API service instance.
* #param String $fileId ID of the file to update permission for.
* #param String $permissionId ID of the permission to patch.
* #param String $newRole The value "owner", "writer" or "reader".
* #return Google_Servie_Drive_Permission The patched permission. NULL is
* returned if an API error occurred.
*/
function patchPermission($service, $fileId, $permissionId, $newRole) {
$patchedPermission = new Google_Service_Drive_Permission();
$patchedPermission->setRole($newRole);
try {
return $service->permissions->patch($fileId, $permissionId, $patchedPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
I am trying to upload a pdf to google drive as a service account in php.
I get a browser error: ERR_CONNECTION_RESET when trying to upload.
I got the code from here:
https://developers.google.com/drive/web/service-accounts#next_steps
and
https://developers.google.com/drive/v2/reference/files/insert
<?php
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'xxx#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'API Project-xxx.p12';
/**
* Build and returns a Drive service object authorized with the service accounts.
*
* #return Google_DriveService service object.
*/
function buildService() {
global $DRIVE_SCOPE, $SERVICE_ACCOUNT_EMAIL, $SERVICE_ACCOUNT_PKCS12_FILE_PATH;
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
array($DRIVE_SCOPE),
$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
/**
* Insert new file.
*
* #param Google_DriveService $service Drive API service instance.
* #param string $title Title of the file to insert, including the extension.
* #param string $description Description of the file to insert.
* #param string $parentId Parent folder's ID.
* #param string $mimeType MIME type of the file to insert.
* #param string $filename Filename of the file to insert.
* #return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
$service=buildService();
$title='test';
$description='qqq';
$parentId='';
$mimeType='application/pdf';
$filename='doc.pdf';
insertFile($service, $title, $description, $parentId, $mimeType, $filename)
?>
I'm trying to upload a local CSV-file to Google Drive and display it like a Google Spreadsheet there. However, when I go to my Google Drive and click the link to my file, I can only download it, not view it as a spreadsheet. I've tried using the ?convert=true but the file doesn't get converted. I've also tried using application/vnd.google-apps.spreadsheet as the mime type but noting changes or I get a 400 Bad request response.
When I right click the file, I can choose to open with Google Spreadsheets which then displays the file correctly. I can't find anything about this in the current documentation over at Google and searches on google haven't help a whole lot.
What I've done so far is creating a new, empty Google spreadsheet and tried filling it with my CSV file but that gives me a 500 Internal Error.
$file = new Google_DriveFile();
$file->setTitle('Exported data from ' . $this->event->title);
$file->setDescription('Exported data from ' . $this->event->title);
$file->setMimeType( 'text/csv' );
try {
$createdFile = $this->drive->files->insert($file, array(
'data' => $data,
'mimeType' => 'application/vnd.google-apps.spreadsheet'
), array('convert'=>true));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
$additionalParams = array(
'newRevision' => false,
'data' => $data,
'convert'=>true //no change if this is true or false
);
$newFile = $this->drive->files->get( $createdFile->getId() );
$newFile->setMimeType('text/csv');
$updated = $this->drive->files->update($createdFile->getId(), $newFile, $additionalParams);
preint_r($updated);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
I've looked at the API for Google Drive but haven't found anything useful. I'm wondering if I should use the Google Spreadsheets API or is the Google Drive API the one to use solely?
Many thanks in advance,
Waldemar
Try the following. It's from the File:insert reference in the Google documentation but I added the convert parameter:
/**
* Insert new file.
*
* #param Google_DriveService $service Drive API service instance.
* #param string $title Title of the file to insert, including the extension.
* #param string $description Description of the file to insert.
* #param string $parentId Parent folder's ID.
* #param string $mimeType MIME type of the file to insert.
* #param string $filename Filename of the file to insert.
* #return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'convert' => true,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
i am try above code it will not working for me
it will just stop after login
just use
$file->setMimeType('application/vnd.google-apps.spreadsheet);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/csv',
'convert' => true,
));
it will work for me
I have to add another parameters to make it work.
'uploadType' => 'multipart'
$createdFile = $service->files->insert($file,array(
'data' => $data,
'mimeType' => 'text/csv',
'convert' => true,
'uploadType' => 'multipart',
));
Now it's working.