Sentiment analysis with PHP
Even better news is you do not need to be an advanced programmer at all, because our implementation of the PHP sentiment analysis client is insanely simple to use. (We believe in the Unix philosophy of building applications that do one thing and do it well.)
Let’s demonstrate this.
Example 1: Sentiment analysis on sentences
We start our PHP code segment with a single inclusion header, indicating we want to use the InterTextueel API library.
We create an object to connect to the InterTextueel API.
$itx = new Intertex(“youruniqueaccesskey”);
We declare a variable with a sentence, such as this one.
$sentence = “Ik ben helemaal klaar met die gast, zo pisnijdig word ik hier van.”
We request an emotion recognition and retrieve the result in a single line:
$result = $itx->sentenceEmotions($sentence);
The result is a typical PHP datastructure: a nested array. Let’s see what it looks like.
["language"]=> string(2) "nl"
["language_autodetected"]=> string(4) "true"
As you can see, the primary emotions happiness, anger, sadness, fear, surprise and disgust are accessible as keys in the response structure.
Example 2: Working on bigger texts
Often we will want to work on a complete-text basis and get an immediate summarization of the mood of a text. If we haven’t done the tokenization of the text ourselves (to separate it into sentences) we can do it on the fly:
$result = $itx->textEmotions(“Die sentiment analyse software werkt echt verbluffend goed. Geen wonder dat iedereen eufoor wordt door het gebruik ervan.”);
The response object of the function above is quite similar to that of the textSentence() method, but we will now see the average scores of emotions in the text.
Passing an array of sentences into the same function is also an option. Our PHP client library will parallelize the requests to the API for you in the background, using asynchronous multi-curl. This reduces the total sentiment analysis time.
Example 3: Simulating traditional sentiment analysis
In the third example we will show how we can perform a more traditional, binary sentiment analysis with PHP.
$positive = $emotions['happiness'];
$negative = array_sum($emotions) – $positive - $emotions['surprise'];
Another option would be to create a tripartite structure, with primary categories: positive emotions, negative emotions, or surprise. Choose the solution which best suits your research question.
A lot of the charts, figures and demos on this website are produced from within PHP. Integrating emotion recognition software into your PHP website or dashboard becomes a breeze using our library.