1. Go to this page and download the library: Download iadj/gcloud library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
iadj / gcloud example snippets
use Google\Cloud\Logging\LoggingClient;
$logging = new LoggingClient([
'projectId' => 'my_project'
]);
// Get a logger instance.
$logger = $logging->logger('my_log');
// Write a log entry.
$logger->write('my message');
// List log entries from a specific log.
$entries = $logging->entries([
'filter' => 'logName = projects/my_project/logs/my_log'
]);
foreach ($entries as $entry) {
echo $entry->info()['textPayload'] . "\n";
}
use Google\Cloud\Datastore\DatastoreClient;
$datastore = new DatastoreClient([
'projectId' => 'my_project'
]);
// Create an entity
$bob = $datastore->entity('Person');
$bob['firstName'] = 'Bob';
$bob['email'] = '[email protected]';
$datastore->insert($bob);
// Update the entity
$bob['email'] = '[email protected]';
$datastore->update($bob);
// If you know the ID of the entity, you can look it up
$key = $datastore->key('Person', '12345328897844');
$entity = $datastore->lookup($key);
use Google\Cloud\Storage\StorageClient;
$storage = new StorageClient([
'projectId' => 'my_project'
]);
$bucket = $storage->bucket('my_bucket');
// Upload a file to the bucket.
$bucket->upload(
fopen('/data/file.txt', 'r')
);
// Using Predefined ACLs to manage object permissions, you may
// upload a file and give read access to anyone with the URL.
$bucket->upload(
fopen('/data/file.txt', 'r'),
[
'predefinedAcl' => 'publicRead'
]
);
// Download and store an object from the bucket locally.
$object = $bucket->object('file_backup.txt');
$object->downloadToFile('/data/file_backup.txt');
use Google\Cloud\Storage\StorageClient;
$storage = new StorageClient([
'projectId' => 'my_project'
]);
$storage->registerStreamWrapper();
$contents = file_get_contents('gs://my_bucket/file_backup.txt');
use Google\Cloud\Translate\TranslateClient;
$translate = new TranslateClient([
'key' => 'your_key'
]);
// Translate text from english to french.
$result = $translate->translate('Hello world!', [
'target' => 'fr'
]);
echo $result['text'] . "\n";
// Detect the language of a string.
$result = $translate->detectLanguage('Greetings from Michigan!');
echo $result['languageCode'] . "\n";
// Get the languages supported for translation specifically for your target language.
$languages = $translate->localizedLanguages([
'target' => 'en'
]);
foreach ($languages as $language) {
echo $language['name'] . "\n";
echo $language['code'] . "\n";
}
// Get all languages supported for translation.
$languages = $translate->languages();
foreach ($languages as $language) {
echo $language . "\n";
}
use Google\Cloud\BigQuery\BigQueryClient;
$bigQuery = new BigQueryClient([
'projectId' => 'my_project'
]);
// Get an instance of a previously created table.
$dataset = $bigQuery->dataset('my_dataset');
$table = $dataset->table('my_table');
// Begin a job to import data from a CSV file into the table.
$job = $table->load(
fopen('/data/my_data.csv', 'r')
);
// Run a query and inspect the results.
$queryResults = $bigQuery->runQuery('SELECT * FROM [my_project:my_dataset.my_table]');
foreach ($queryResults->rows() as $row) {
print_r($row);
}
use Google\Cloud\Language\LanguageClient;
$language = new LanguageClient([
'projectId' => 'my_project'
]);
// Analyze a sentence.
$annotation = $language->annotateText('Greetings from Michigan!');
// Check the sentiment.
if ($annotation->sentiment() > 0) {
echo "This is a positive message.\n";
}
// Detect entities.
$entities = $annotation->entitiesByType('LOCATION');
foreach ($entities as $entity) {
echo $entity['name'] . "\n";
}
// Parse the syntax.
$tokens = $annotation->tokensByTag('NOUN');
foreach ($tokens as $token) {
echo $token['text']['content'] . "\n";
}
use Google\Cloud\PubSub\PubSubClient;
$pubSub = new PubSubClient([
'projectId' => 'my_project'
]);
// Get an instance of a previously created topic.
$topic = $pubSub->topic('my_topic');
// Publish a message to the topic.
$topic->publish([
'data' => 'My new message.',
'attributes' => [
'location' => 'Detroit'
]
]);
// Get an instance of a previously created subscription.
$subscription = $pubSub->subscription('my_subscription');
// Pull all available messages.
$messages = $subscription->pull();
foreach ($messages as $message) {
echo $message->data() . "\n";
echo $message->attribute('location');
}
use Google\Cloud\Vision\VisionClient;
$vision = new VisionClient([
'projectId' => 'my_project'
]);
// Annotate an image, detecting faces.
$image = $vision->image(
fopen('/data/family_photo.jpg', 'r'),
['faces']
);
$annotation = $vision->annotate($image);
// Determine if the detected faces have headwear.
foreach ($annotation->faces() as $key => $face) {
if ($face->hasHeadwear()) {
echo "Face $key has headwear.\n";
}
}
use Google\Cloud\Spanner\SpannerClient;
$spanner = new SpannerClient([
'projectId' => 'my_project'
]);
$db = $spanner->connect('my-instance', 'my-database');
$userQuery = $db->execute('SELECT * FROM Users WHERE id = @id', [
'parameters' => [
'id' => $userId
]
]);
$user = $userQuery->rows()->current();
echo 'Hello ' . $user['firstName'];
use Google\Cloud\Speech\SpeechClient;
$speech = new SpeechClient([
'projectId' => 'my_project',
'languageCode' => 'en-US'
]);
// Recognize the speech in an audio file.
$results = $speech->recognize(
fopen(__DIR__ . '/audio_sample.flac', 'r')
);
foreach ($results as $result) {
echo $result->topAlternative()['transcript'] . "\n";
}
use Google\Cloud\VideoIntelligence\V1beta1\VideoIntelligenceServiceClient;
use google\cloud\videointelligence\v1beta1\Feature;
$client = new VideoIntelligenceServiceClient();
$inputUri = "gs://example-bucket/example-video.mp4";
$features = [
Feature::LABEL_DETECTION,
];
$operationResponse = $client->annotateVideo($inputUri, $features);
$operationResponse->pollUntilComplete();
if ($operationResponse->operationSucceeded()) {
$results = $operationResponse->getResult();
foreach ($results->getAnnotationResultsList() as $result) {
foreach ($result->getLabelAnnotationsList() as $labelAnnotation) {
echo "Label: " . $labelAnnotation->getDescription() . "\n";
}
}
} else {
$error = $operationResponse->getError();
echo "error: " . $error->getMessage() . "\n";
}
use Google\Cloud\Trace\TraceClient;
$traceClient = new TraceClient([
'projectId' => 'my_project'
]);
// Create a Trace
$trace = $traceClient->trace();
$span = $trace->span([
'name' => 'main'
]);
$span->setStart();
$span->setEnd();
$trace->setSpans([$span]);
$traceClient->insert($trace);
// List recent Traces
foreach($traceClient->traces() as $trace) {
var_dump($trace->traceId());
}
use Google\Cloud\Storage\StorageClient;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
// Please take the proper precautions when storing your access tokens in a cache no matter the implementation.
$cache = new ArrayAdapter();
$storage = new StorageClient([
'authCache' => $cache
]);
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.