|
20 | 20 | require __DIR__ . '/vendor/autoload.php';
|
21 | 21 |
|
22 | 22 | # Imports the Google Cloud client library
|
23 |
| -use Google\Cloud\Language\LanguageClient; |
| 23 | +use Google\Cloud\Language\V2\AnalyzeSentimentRequest; |
| 24 | +use Google\Cloud\Language\V2\Client\LanguageServiceClient; |
| 25 | +use Google\Cloud\Language\V2\Document; |
24 | 26 |
|
25 | 27 | # Your Google Cloud Platform project ID
|
26 | 28 | $projectId = 'YOUR_PROJECT_ID';
|
27 | 29 |
|
28 | 30 | # Instantiates a client
|
29 |
| -$language = new LanguageClient([ |
| 31 | +$language = new LanguageServiceClient([ |
30 | 32 | 'projectId' => $projectId
|
31 | 33 | ]);
|
32 | 34 |
|
33 | 35 | # The text to analyze
|
34 | 36 | $text = 'Hello, world!';
|
| 37 | +$document = (new Document()) |
| 38 | + ->setContent($text) |
| 39 | + ->setType(Document\Type::PLAIN_TEXT); |
| 40 | +$analyzeSentimentRequest = (new AnalyzeSentimentRequest()) |
| 41 | + ->setDocument($document); |
35 | 42 |
|
36 | 43 | # Detects the sentiment of the text
|
37 |
| -$annotation = $language->analyzeSentiment($text); |
38 |
| -$sentiment = $annotation->sentiment(); |
| 44 | +$response = $language->analyzeSentiment($analyzeSentimentRequest); |
| 45 | +foreach ($response->getSentences() as $sentence) { |
| 46 | + $sentiment = $sentence->getSentiment(); |
| 47 | + echo 'Text: ' . $sentence->getText()->getContent() . PHP_EOL; |
| 48 | + printf('Sentiment: %s, %s' . PHP_EOL, $sentiment->getScore(), $sentiment->getMagnitude()); |
| 49 | +} |
39 | 50 |
|
40 |
| -echo 'Text: ' . $text . ' |
41 |
| -Sentiment: ' . $sentiment['score'] . ', ' . $sentiment['magnitude']; |
42 | 51 | # [END language_quickstart]
|
43 |
| -return $sentiment; |
| 52 | +return $sentiment ?? null; |
0 commit comments