|
Integrating Google search into your site using ColdFusion and XML |
This article examines how you can create and integrate a Google site search into your site. We will query Google and return an XML packet, which we will translate and display within our sites framework.
I am using XML as I must parse the result myself for Accessability. There are a few different ways of returning result, including some really nice AJAX stuff. None of them are Accessable for disabled users though.
To start with go here: http://www.google.co.uk/sitesearch
You can setup a free or Business account. This allows you to specify which sites the search will index, and any exclusions or filtering rules you want. The main difference between the free and Business accounts is the control you have over advertising.
The first step to create a simply search form, the simple form below will submit a form value to a processing template that we will build below.
2<label for="q">Search:</label> <input type="text" name="q" id="q">
3</form>
Next we need to create the template that will handle the form value, and process the results (page.cfm from the form above). The first step is to create a url string that we will use in a cfhttp request. This fires your form value to Google. We also specify that we want the return in an XML format. The http request is parsed using xmlParse.
2<h1>Search results</h1>
3
4<cfif not len(attributes.q)>
5Please enter some search text
6<cfelse>
7
8<cfset variables.url = "http://www.google.com/cse?cx=YOUR_ACCOUNT_NUMBER&client=google-csbe&output=xml_no_dtd&q=">
9<cfset variables.url = variables.url & attributes.q>
10
11<cfhttp url="#arguments.url#" method="get" result="variables.response"></cfhttp>
12
13<cfscript>
14 xmlfile = xmlparse(variables.response.filecontent);
15</cfscript>
16
17<cftry>
18<cfset arrEntries = variables.response.gsp.res.r>
19<cfcatch>
20<!--- no response --->
21<cfset variables.noResults = true>
22</cfcatch>
23</cftry>
In the next block of code we check that we successfully parsed the XML and that we have a valid Array. Then we loop over the results Array setting the values we want. Then display them on the page.
2<p>There were no results for your search using <strong>#attributes.q#</strong></p>
3<cfelse>
4<p>Below are the results for your search on '<strong>#attributes.q#</strong>'</p>
5<p></p>
6
7<cfloop index="i" from="1" to="#ArrayLen(arrEntries)#">
8<cfset properties["searchTitle"] = arrEntries[i].XmlChildren[3].XmlText>
9<cfset properties["searchString"] = arrEntries[i].XmlChildren[5].XmlText>
10<cfset properties["searchUrl"] = arrEntries[i].XmlChildren[1].XmlText>
11
12<h3 class="search-header"><a href="#properties.searchUrl#" title="#properties.searchTitle#" target="_blank">#properties.searchTitle#</a></h3>
13
14<div>#properties.searchString#</div>
15<br>
16</cfloop>
17</cfif>
18</cfif>
The returned XML packet has a lot more data in it than just the three values I am using, so you could expand on this.