Keyword Discovery - API examples
Below are some examples of API integration using other languages.
Languages not listed in the examples can also be used.
Contents
Perl
Example Code snippet
use CGI; use LWP; use XML::LibXSLT; use XML::LibXML; use URI::Escape; my $username = 'username'; my $password = 'password'; my $q = new CGI; my $ua = LWP::UserAgent->new; my $request_url = 'http://' . uri_escape($username) . ":" . uri_escape($password) . '@api.keyworddiscovery.com/free.php'; my %params = $q->Vars; my $res = $ua->post($request_url,\%params); if ($res->is_success) { print $q->header(-charset=>'utf8'); my $parser = XML::LibXML->new(); my $xslt = XML::LibXSLT->new(); my $xml_data = $parser->parse_string($res->content); my $style_doc = $parser->parse_file('output_template.xsl'); my $stylesheet = $xslt->parse_stylesheet($style_doc); my $results = $stylesheet->transform($xml_data); print $stylesheet->output_string($results); } else { print $q->header(-charset=>'utf8'), $q->start_html('Auth Error Error'), $q->h1('Auth Error'), 'Server Setup Error: invalid authentication details'; }
PHP
Example Code Snippet -- FREE API
<?php $username = 'username'; $password = 'password'; $search_phrase = 'search phrase'; $request_url = sprintf( 'http://%s:%s@api.keyworddiscovery.com/free.php?q=%s', urlencode($username), urlencode($password), urlencode($search_phrase) ); $res = file_get_contents($request_url); if ($res != '') { $arguments = array( '/_xml' => $res, '/_xsl' => file_get_contents('output_template.xsl') ); // Allocate a new XSLT processor $xh = xslt_create(); // Process the document $result = xslt_process($xh, 'arg:/_xml', 'arg:/_xsl', NULL, $arguments); if ($result) { print $result; } else { printf('Transform error [%s] code [%d]',xslt_error($xh),xslt_errno($xh)); } xslt_free($xh); } ?>
Example Code Snippet -- Enterprise API
<?php // Provide credentials $username = 'username'; $password = 'password'; $query = 'search'; // Search term can be feed to the script, hard coded here for illustration purposes // Query Keyword Discovery search interface $request_url = "http://".urlencode($username).":".urlencode($password). "@api.keyworddiscovery.com/query.php?q=".urlencode($query); $res = fetch_url($request_url); // Parse the fetched XML Results $results = array(); $res_lines = preg_split("/[\n\r]+/", $res); array_shift($res_lines); // Discard xml header $summary = array_shift($res_lines); if (preg_match('|estimated_total="(\d+)"|', $summary, &$matches) == 1) { $estimated_total = $matches[1]; }// end if foreach ($res_lines as $line) { if (preg_match('|<r m="(\d+)" q="([^"]+)" t="(\d+)" />|', $line, &$matches) == 1) { $m = $matches[1]; $q = $matches[2]; $t = $matches[3]; echo "$q,$t<br>"; }// end if }// end foreach // Function for fetching urls function fetch_url($url, $code_on_fail = false, $interface = null) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); if ($interface !== null) { curl_setopt($ch, CURLOPT_INTERFACE, $interface); }// end if $content = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($content === false && $code_on_fail === true) { return $http_code; }// end if return $content; }// end function ?>
C#.Net
The C# code example was provided by a 3rd party and is provided as is and may need additional coding to work.
Example Code snippet
<%@ Page Language="C#" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.Xml.Xsl" %> <%@ Import Namespace="System.Web" %> <%@ Import Namespace="System.Net" %> <script language="C#" runat="server"> void Page_Load(Object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); NetworkCredential networkCredential = new NetworkCredential("username","password"); HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create( "http://api.keyworddiscovery.com/free.php?q=" + HttpUtility.UrlEncode(Request.Form["query"]) ); HttpWReq.PreAuthenticate = true; HttpWReq.Credentials = networkCredential; HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse(); if (HttpWResp.StatusCode == HttpStatusCode.OK) { doc.Load(HttpWResp.GetResponseStream()); } XslTransform trans = new XslTransform(); trans.Load(Server.MapPath("output_template.xsl")); xml1.Document = doc; xml1.Transform = trans; } </script> <asp:Xml id="xml1" runat="server" />
Example output_template.xsl XSL file
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp " "> <!ENTITY sp "	"> <!ENTITY nbhy "‑"> ]> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html" indent="yes" version="4.0" omit-xml-declaration="yes"/> <xsl:template match="/"> <html> <head> <title>Query Results</title> </head> <body> <center> <form method="post" name="search_form" action="free.cgi"> <p class="copy"><b>Enter a keyword:</b><br /> <input type="text" name="query" /> <input type="submit" value="Search" /></p> <xsl:for-each select="resultset/results"> <div style="float: left;" align="left"> <h3 class="lhcopy">Query: <xsl:value-of select="@query" /></h3> <table class="sortable" id="{generate-id(@query)}" border="0" cellspacing="1" style="margin-bottom: 10px;"> <thead> <tr> <th align="center">query</th> <th align="center" sortfn="ts_sort_currency">total</th> </tr> </thead> <tbody> <xsl:for-each select="r"> <tr class="row{position() mod 2}"> <td class="q"> <a href="#"><xsl:attribute name="onclick">document.search_form.query.value = '<xsl:value-of select="@q" />'; document.search_form.submit();</xsl:attribute><xsl:value-of select="@q" /></a></td> <td class="t"><xsl:value-of select="format-number(@t, '###,###')" /></td> </tr> </xsl:for-each> </tbody> </table> </div> </xsl:for-each> </form> <br/><br/> <div id="providedby" class="copy" style="clear: both;"> Keywords provided by KeywordDiscovery.com<br/> For more results visit <a href="http://www.keyworddiscovery.com">KeywordDiscovery.com</a> </div> </center> </body> </html> </xsl:template> </xsl:stylesheet>