How to query Microsoft Cognitive Service Text Analytics API using cURL in PHP (example code)

The following example shows a simple example of how to query Microsoft Cognitive Service Text Analytics API by posting JSON array through cURL in PHP and extract the entities.

The Text Analytics API is a web service that can interpret the un-organized text for tasks such as sentiment summary, keyphrase extraction and language discovery. Just post the text data and API will use exceptional NLP processing methods to achieve best in class predictions.

The reason I have created this post is due to Microsoft presenting an example PHP code on their website that uses the Apache HTTP client from HTTP Components to accomplish querying of Text Analytics API in PHP. However, I couldn’t get the code working for me, hitting various obstacles with that approach, so I decided to rework the query script to PHP cURL.

It took me a while to figure this out, so I am sharing it in case someone comes across similar issues.

Here is a copy of the working code that sends a sample text (‘Microsoft released Windows 10’) over to API.

Make sure to read the comments in CAPS:

The above example code would generate the Array that looks like this:

If you wish you can parse out just name entities, this is how you would do it. Just comment out the <pre> section and add this to the bottom of the PHP code and :

It’ll generate:

These are essentially the names of Wikipedia articles discovered by Microsoft Cognitive Service Text Analytics API in the sample text (‘Microsoft released Windows 10’).

If you want WIKI urls, just echo $return[documents][0][entities][$i][wikipediaUrl] instead.

I hope this helped.

Comments

comments