PHP Code Sample
PHP code that connects to the OpenAmplify open API, submits a request, receives the XML output, and provides an example of navigating the XML.
File has been updated for use with OpenAmplify Version 2.0
Overview:
A very convenient way to submit and retrieve data with the OpenAmplify API is by using the cURL libraries available in PHP. Setup and installation of cURL are covered here.
Setting parameters:
Setting the parameters is as simple as placing them as a string in a cURL object's curl_setopt() method. To maintain readability though, we'll first declare the parameters as their own variables, then combine them and urlencode them into a single string ($post) that can be submitted to the curl_setopt() method.
Set the parameters: ---------------------------- $apiKey = '12345'; // Insert your API key here. $analysis = 'all'; // all (default), actions, topics, demographics, styles. $outputFormat = 'xml'; // xml (default), json, dart. // select either this option or the following... not both. $sourceURL = 'http://www.nytimes.com'; // $inputText = 'Lorem ipsum...'; Combine parameters: $post = 'apiKey=' . urlencode($apiKey) . '&analysis=' . urlencode($analysis) . '&outputFormat=' . urlencode($outputFormat) . '&sourceURL=' . urlencode($sourceURL); // '&inputText=' . urlencode($inputText); // ------------------------------------------------------ Place parameters in cURL object: ------------------------------------------- $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'http://portaltnx20.openamplify.com/AmplifyWeb_v21/AmplifyThis'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
Issue request:
Use the cURL curl_exec() method to submit the cURL object with its parameters and url.
$result = curl_exec ($ch); curl_close ($ch);
The $result variable now contains the text received from the API, which we can parse however we want.
Parse XML
For a full discussion of the XML output, click that link back there. You know how the Internet works.
Since the API's output is XML in this case, the smartest approach is to use a simple XML object for storage and parsing of the data:
// initialize a SimpleXML object. $xml = new SimpleXMLElement($result);
From here, you can do whatever XPath searches you like to find the data that's returned.
XPath examples:
// Now just do some XPath searches.
echo "Topics:\n";
foreach ($xml->xpath('//Topic') as $n) {
echo "\t" . $n->Name . "\n";
}
echo "Actions:\n";
foreach ($xml->xpath('//Action') as $n) {
echo "\t" . $n->Name . "\n";
}
echo "Demographics:\n";
foreach ($xml->xpath('//Demographics') as $n) {
echo "\tAge: " . $n->Age->Name . "\n";
echo "\tGender: " . $n->Gender->Name . "\n";
echo "\tEducation: " . $n->Education->Name . "\n";
}
echo "Style:\n";
foreach ($xml->xpath('//Styles') as $n) {
echo "\tSlang: " . $n->Slang->Name . "\n";
echo "\tFlamboyance: " . $n->Flamboyance->Name . "\n";
}Bugs and features:
At present PHP works smoothly.
