Creating Freebase applications with PHP5

Writing Freebase apps in PHP5 is very easy since PHP5 has built-in support for JSON structures, the format of the Metaweb Query Language (MQL.) And almost all PHP5 instances are compiled with cURL support which makes performing GET requests a snap!

This page takes you through the two small steps necessary to write a Freebase application: creating a MQL query through PHP's JSON methods and sending the query to the Freebase API using cURL. The final script, shown at the bottom of the page, also demonstrates how easy it is to add Freebase Suggest to an application.

Creating JSON structures is simply a matter of combining various array structures (both associative and sequential) and calling json_encode on the structure. For example to create the JSON structure:

{"id":"/topic/en/philip_k_dick", "/film/writer/film":[]}

You would call:

$simplequery = array('id'=>'/topic/en/philip_k_dick', '/film/writer/film'=>array());
$jsonquerystr = json_encode($simplequery);

The Freebase API requires a query envelope (which allows you to run multiple queries simultaneously) so we need to wrap our original, simplequery structure in two more arrays before we can pass it to the API:

$queryarray = array('q1'=>array('query'=>$simplequery));
$jsonquerystr = json_encode($queryarray);

To send the JSON formatted MQL query to the Freebase API use cURL:

#run the query
$apiendpoint = "http://sandbox.freebase.com/api/service/mqlread?queries";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jsonresultstr = curl_exec($ch);
curl_close($ch); 

Decoding the JSON structure back into arrays is performed using json_decode as in:

$resultarray = json_decode($jsonresultstr, true); #true:give us the json struct as an array

Iterating over the piece of the resultarray containing films gives us the films Philip K. Dick wrote:

$filmarray = $resultarray["q1"]["result"]["/film/writer/film"];

foreach($filmarray as $film){
	print "$film<br>";
}

Putting this all together and using Freebase Suggest to let the user pick the writer:

[Note the name of this file is assumed to be index.php - the name of the page in the form action parameter below. (i.e., the page submits to itself.)]

<head>	
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
  <link type="text/css" rel="stylesheet" href="http://freebaselibs.com/static/suggest/1.0.1/suggest.min.css" />

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script type="text/javascript" src="http://freebaselibs.com/static/suggest/1.0.1/suggest.min.js"></script>

</head>

<script type="text/javascript">
$(function() {
   $("#writerinput")
      .suggest({'type': '/film/writer'})
      .bind("fb-select", function(e, data) {          
         $('#writer').val(data.id);
    });
});
</script>

<form method=post action=index.php>
Writer: <input type="text" id="writerinput" />

<input type=hidden name=freebasewriter id=writer>
<input type=submit value="Find Films">
</form><p>

<?php

if($_POST["freebasewriter"] != null){
	
	#slightly fancier - get the name and id of each of the films in the array
	$simplequery = array('id'=>$_POST["freebasewriter"], 'name'=>null, '/film/writer/film'=>array(array('name'=>null, 'id'=>null)));
	
	$queryarray = array('q1'=>array('query'=>$simplequery));
	$jsonquerystr = json_encode($queryarray);
	
	#run the query
	$apiendpoint = "http://sandbox.freebase.com/api/service/mqlread?queries";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, "$apiendpoint=$jsonquerystr");
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$jsonresultstr = curl_exec($ch);
	curl_close($ch); 
	
	$resultarray = json_decode($jsonresultstr, true);
	
	$writername = $resultarray["q1"]["result"]["name"]; 
	$filmarray = $resultarray["q1"]["result"]["/film/writer/film"];
	$freebaseserver = "http://sandbox.freebase.com";
	
	print "<h2>Films by: $writername</h2>";
	
	if(count($filmarray > 0)){
	   foreach($filmarray as $film){
	      $filmname = $film['name'];
	      $filmid = $film['id'];
	      print "<a href=$freebaseserver/view/$filmid>$filmname</a><br>";
	   }
	}
}
?>

<p>
<div style="font-size: x-small">
<img src="http://www.freebase.com/api/trans/raw/freebase/attribution" 
style="float:left; margin-right: 5px" />
<div style="margin-left="30px"> Source: 
<a href="http://www.freebase.com" title="Freebase – The World's Database">Freebase</a> 
– The World&apos;s Database <br/> Freely licensed under 
<a href="http://www.freebase.com/view/common/license/cc_attribution_25">CC-BY</a>. 

</div> </div>

Note: there is more information on PHP and Freebase on the Wiki at:
http://wiki.freebase.com/wiki/Read_API_Code_Snippets#PHP and http://wiki.freebase.com/wiki/PHP