Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Sparql Query Builder

Sparql Query Builder class can be used to compose queries to XML RDF documents using SPARQL.

It can compose and generate queries for sending to a SPARQL end point that can extract semantic information from RDF documents.

It complies with W3C Recommendations http://www.w3.org/TR/rdf-sparql-query/

This class reduces amount of text needs to be written comparing to simply writing SPARQL queries, increases code readability and helps you to create user friendly interfaces for SPARQL endpoints.

Here is an example of how to Implementing RDF and Sparql using ARC solution

Contents

Download

Example codes

<?php
//This is an example usage of SPARQL Query Builder
//Here you can find some examples from W3C Recommendation 
//http://www.w3.org/TR/rdf-sparql-query/
//And specific class examples


//declaring class instance
include("./sparql.class.php");
$sparql = new sparql();

//outputs only end query for debug purpose
$sparql->show_query();

//outputs step by step debug information
//$sparql->debug();

/****************************************
 * example of sparql query 
 * from http://www.w3.org/TR/rdf-sparql-query/#MultipleMatches
 * PREFIX foaf:   <http://xmlns.com/foaf/0.1/>
 * SELECT ?name ?mbox
 * WHERE
 * { ?x foaf:name ?name .
 *   ?x foaf:mbox ?mbox }
 *****************************************/
//defining prefix
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
//adding what to select
$sparql->select("?name");
$sparql->select("?mbox");

//creating patterns with full graph
$sparql->new_ptrn("?x foaf:name ?name .");
//creating empty pattern,
$pat = $sparql->new_ptrn("");
//adding node after pattern creation
//patterns are interpreted as string, so we may 
//add multiple patterns as one pattern, but they need to be in one clause
// or add nodes one by one, which will form pattern string
$sparql->add_ptrn($pat, "?x");
$sparql->add_ptrn($pat, "foaf:mbox ?mbox .");

//no need to add patterns to where clause, all unused patterns 
//will automatically get to where clause if union wasn't used
//if union was used, then new union will be created and 
//all unused patterns will go there

//generating query
$query = $sparql->query();
?>

Examples in action

Example scripts provided with package in action:

Method list

Provide debug information

Back to method list

Method namedebug()
Descriptionoutputs information about every sparql query building step and outputs query itself in the end

Output query in the end

Back to method list

Method nameshow_query()
DescriptionOutputs query when building process is complete, without any debug information

Add new prefix to query

Back to method list

Method nameprefix($name, $prefix)
DescriptionAdds new prefix to query.
Input parameters

string $name - abbreviation of prefix

string $prefix - prefix URI - universal resource identifier

Example usage
//defining prefix
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
//adding what to select
$sparql->select("?name");
$sparql->select("?mbox");

//creating patterns with full graph
$sparql->new_ptrn("?x foaf:name ?name .");
//creating empty pattern,
$pat = $sparql->new_ptrn("");
//adding node after pattern creation
//patterns are interpreted as string, so we may add multiple 
//patterns as one pattern, but they need to be in one clause
// or add nodes one by one, which will form pattern string
$sparql->add_ptrn($pat, "?x");
$sparql->add_ptrn($pat, "foaf:mbox ?mbox .");

SELECT type query

Back to method list

Method nameselect($sel)
DescriptionSets query type to select and provides information which nodes to select. Default query type is SELECT type.
Input parameters

string $sel - nodes to select or "*" to select all

Example usage
//defining prefix
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
//specifying what to select
$sparql->select("?title");

//pattern for where clause
$sparql->new_ptrn("?x dc:title ?title");
$sparql->new_ptrn("FILTER regex(?title, 'web', 'i' )");

//generating query
$query = $sparql->query();

DESCRIBE type query

Back to method list

Method namedescribe($sub)
DescriptionSets query type to describe and provides information which nodes to describe
Input parameters

string $sub - nodes to describe or "*" to describe all

Example usage
//adding prefix
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");

//using describe type query
$sparql->describe("?x");

//new pattern
$sparql->new_ptrn("?x foaf:mbox ");

//generating query
$query = $sparql->query();

Define SELECT type

Back to method list

Method nameselect_type($type)
DescriptionSets SELECT type query to REDUSED or DISTINCT
Input parameters

string $type - select type

Example usage
//adding prefixes
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");

//selecting node
$sparql->select("?name");
//specifying select type
$sparql->select_type("distinct");

//new pattern
$sparql->new_ptrn("?x foaf:name ?name");

//generating query
$query = $sparql->query();

CONSTRUCT clause

Back to method list

Method nameconstruct($cnt)
DescriptionAdd pattern to construct clause
Input parameters

int $cnt - pattern identifier returned by method new_ptrn. Multiple patterns can be added.

Example usage
//defining prefixes
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
$sparql->prefix("org", "http://example.com/ns#");

//creating pattern for construct
$pat = $sparql->new_ptrn("?x foaf:name ?name");
//pattern for where clause
$sparql->new_ptrn("?x org:employeeName ?name");
//adding pattern to construct clause
$sparql->construct($pat);

//generating query
$query = $sparql->query();

ASK clause

Back to method list

Method nameask($cnt)
DescriptionAdd pattern to ask clause
Input parameters

int $cnt - pattern identifier returned by method new_ptrn. Multiple patterns can be added.

Example usage
//adding prefix
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");

//new pattern
$pat = $sparql->new_ptrn("'?x foaf:name  "Alice"');

//adding pattern to ask
$sparql->ask($pat);

//generating query
$query = $sparql->query();

Create new pattern

Back to method list

Method namenew_ptrn($graph)
DescriptionPatterns consists of nore triplets and are basic elements of query building. You can create patterns with nodes and then use them in different clause by specifying pattern identifier which is returned by this method. Once pattern is used in any clause it is deleted and cannot be modified. All unused patterns will be added to where clause in the query building process
Input parameters

string $graph - One or multiple nodes or empty pattern for later use.

Example usage
//defining prefixes
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
$sparql->prefix("org", "http://example.com/ns#");

//creating pattern for construct
$pat = $sparql->new_ptrn("?x foaf:name ?name");
//pattern for where clause
$sparql->new_ptrn("?x org:employeeName ?name");
//adding pattern to construct clause
$sparql->construct($pat);

//generating query
$query = $sparql->query();

Add nodes to existing pattern

Back to method list

Method nameadd_ptrn($cnt, $graph)
DescriptionAdd one or mutiple nodes to existing pattern by specifying pattern identifier from new_ptrn method
Input parameters

int $cnt - pattern identifier

string $grpah - one or multiple nodes

Example usage
//defining prefix
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
//adding what to select
$sparql->select("?name");
$sparql->select("?mbox");

//creating patterns with full graph
$sparql->new_ptrn("?x foaf:name ?name .");
//creating empty pattern,
$pat = $sparql->new_ptrn("");
//adding node after pattern creation
//patterns are interpreted as string, so we may add 
//multiple patterns as one pattern, but they need to be in one clause
// or add nodes one by one, which will form pattern string
$sparql->add_ptrn($pat, "?x");
$sparql->add_ptrn($pat, "foaf:mbox ?mbox .");

//no need to add patterns to where clause, all unused patterns 
//will automatically get to where clause if union wasn't used
//if union was used, then new union will be created 
//and all unused patterns will go there

//generating query
$query = $sparql->query();

WHERE clause

Back to method list

Method namewhere($cnt)
DescriptionAdd pattern to where clause. Note: all defined, but unused patterns are automatically added to where clause in the end of query building process
Input parameters

int $cnt - pattern identifier returned by method new_ptrn. Multiple patterns can be added.

Example usage

where(new_ptrn("?a ?b ?c."))

OPTIONAL clause

Back to method list

Method nameoptional($cnt, $opt = "")
DescriptionAdd pattern to optional clause. You can create multipl optional clauses. If second parameter isn't provided, new clause will be created and optional clause identifier returned. You can provide valid optional clause identifier (returned by this function) to add pattern to specific optional clause
Input parameters

int $cnt - pattern identifier returned by method new_ptrn

int $opt - optional clause identifier to specify in which optional clause to incldue pattern. If not specified, new optional clause will be created and it's identfier returned

Example usage
//defining prefix
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
//specifying what to select
$sparql->select("?name ?mbox ?hpage");

//pattern for where clause
$sparql->new_ptrn("?x foaf:name ?name");
//array for optional patterns
$optionals = array();
//creating patterns which wil be used in option clauses
$optionals[] = $sparql->new_ptrn("?x foaf:mbox ?mbox");
$optionals[] = $sparql->new_ptrn("?x foaf:homepage ?hpage");

//putting patterns in optional clauses
foreach($optionals as $optional)
{
	$sparql->optional($optional);
}


//generating query
$query = $sparql->query();

GRAPH clause

Back to method list

Method namegraph($cnt, $opt = "")
DescriptionAdd pattern to graph clause. You can create multiple graph clauses. If second parameter isn't provided, new clause will be created and graph clause identifier returned. You can provide valid graph clause identifier (returned by this function) to add pattern to specific graph clause
Input parameters

int $cnt - pattern identifier returned by method new_ptrn

int $opt - graph clause identifier to specify in which graph clause to incldue pattern. If not specified, new graph clause will be created and it's identfier returned

Example usage
//defining prefixes
$sparql->prefix("data", "http://example.org/foaf/");
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
$sparql->prefix("rdfs", "http://www.w3.org/2000/01/rdf-schema#");

$sparql->select("?mbox ?nick ?ppd");

//specifying sources
$sparql->from_named("http://example.org/foaf/aliceFoaf");
$sparql->from_named("http://example.org/foaf/bobFoaf");

//storage for first graph
$graphs["data:aliceFoaf"] = array();
//sotrage for second graph
$graphs["?ppd"] = array();

//creating needed patterns
$graphs["data:aliceFoaf"][] = $sparql->new_ptrn("?alice foaf:mbox  ;");
$graphs["data:aliceFoaf"][] = $sparql->new_ptrn("foaf:knows ?whom .");
$graphs["data:aliceFoaf"][] = $sparql->new_ptrn("?whom  foaf:mbox ?mbox ;");
$graphs["data:aliceFoaf"][] = $sparql->new_ptrn("rdfs:seeAlso ?ppd .");
$graphs["data:aliceFoaf"][] = $sparql->new_ptrn("?ppd  a 
				foaf:PersonalProfileDocument .");
$graphs["?ppd"][] = $sparql->new_ptrn("?w foaf:mbox ?mbox ;");
$graphs["?ppd"][] = $sparql->new_ptrn("foaf:nick ?nick");

//adding patterns to grpahs
foreach($graphs as $key => $graph)
{
	foreach($graph as $value)
	{
		$sparql->graph($value, $key);
	}
}

//generating query
$query = $sparql->query();

SELECT FROM

Back to method list

Method namefrom($value)
DescriptionSpecify URL source from which to select data
Input parameters

string $value - source URL

Example usage
//defining prefixes
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
$sparql->prefix("dc", "http://purl.org/dc/elements/1.1/");

$sparql->select("?who ?g ?mbox");

//specifying sources
$sparql->from("http://example.org/dft.ttl");
$sparql->from_named("http://example.org/alice");
$sparql->from_named("http://example.org/bob");

//creating pattern
$pat = $sparql->new_ptrn("?book dc11:title ?title .");
//adding to whre clause, to put this pattern in the beggining of where clause
$sparql->where($pat);
//creating pattern for graph
$pat = $sparql->new_ptrn("?x foaf:mbox ?mbox");
//putting pattern into graph
$sparql->graph($pat, "?g");

//generating query
$query = $sparql->query();

SELECT FROM NAMED

Back to method list

Method namefrom_named($value)
DescriptionSpecify URI source from which to select data
Input parameters

string $value - source URI

Example usage
//defining prefixes
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
$sparql->prefix("dc", "http://purl.org/dc/elements/1.1/");

$sparql->select("?who ?g ?mbox");

//specifying sources
$sparql->from("http://example.org/dft.ttl");
$sparql->from_named("http://example.org/alice");
$sparql->from_named("http://example.org/bob");

//creating pattern
$pat = $sparql->new_ptrn("?book dc11:title ?title .");
//adding to whre clause, to put this pattern in the beggining of where clause
$sparql->where($pat);
//creating pattern for graph
$pat = $sparql->new_ptrn("?x foaf:mbox ?mbox");
//putting pattern into graph
$sparql->graph($pat, "?g");

//generating query
$query = $sparql->query();

Add patterns to all union clauses

Back to method list

Method nameunion_h($cnt)
DescriptionUnion head contains patterns that will be included in every union clause
Input parameters

int $cnt - pattern identifier returned by method new_ptrn

Example usage
//adding prefix
$sparql->prefix("table", 
	"http://www.daml.org/2003/01/periodictable/PeriodicTable#");

//selecting nodes
$sparql->select("?symbol ?number");
//selectgin source
$sparql->from("http://www.daml.org/2003/01/periodictable/PeriodicTable#");

//union head patterns, which will be used in every union clause
$head1 = $sparql->new_ptrn("?element table:symbol ?symbol;");
$head2 = $sparql->new_ptrn("?element table:atomicNumber ?number;");

//patterns for different union clauses
$union1 = $sparql->new_ptrn("?element table:group table:group_17.");
$union2 = $sparql->new_ptrn("?element table:group table:group_18.");

//adding union head patterns
$sparql->union_h($head1);
$sparql->union_h($head2);

//adding union pattern, we need to add only one, 
//other will be automatically included in new union clause
$sparql->union($union1);

//generating query
$query = $sparql->query();

UNION clause

Back to method list

Method nameunion($cnt, $opt = "")
DescriptionAdd pattern to union clause. You can create multiple union clauses. If second parameter isn't provided, new clause will be created and union clause identifier returned. You can provide valid union clause identifier (returned by this function) to add pattern to specific union clause. NOTE: To add pattern to all defined union clause use union_h method
Input parameters

int $cnt - pattern identifier returned by method new_ptrn

int $opt - union clause identifier to specify in which union clause to incldue pattern. If not specified, new union clause will be created and it's identfier returned

Example usage
//adding prefix
$sparql->prefix("table", 
	"http://www.daml.org/2003/01/periodictable/PeriodicTable#");

//selecting nodes
$sparql->select("?symbol ?number");
//selectgin source
$sparql->from("http://www.daml.org/2003/01/periodictable/PeriodicTable#");

//union head patterns, which will be used in every union clause
$head1 = $sparql->new_ptrn("?element table:symbol ?symbol;");
$head2 = $sparql->new_ptrn("?element table:atomicNumber ?number;");

//patterns for different union clauses
$union1 = $sparql->new_ptrn("?element table:group table:group_17.");
$union2 = $sparql->new_ptrn("?element table:group table:group_18.");

//adding union head patterns
$sparql->union_h($head1);
$sparql->union_h($head2);

//adding union pattern, we need to add only one, 
//other will be automatically included in new union clause
$sparql->union($union1);

//generating query
$query = $sparql->query();

LIMIT result

Back to method list

Method namelimit($lim)
DescriptionLimit result to specified number
Input parameters

int $cnt - how many maximum results to return. Limit number must be bigger than zero

Example usage
//adding prefixes
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");

//selecting node
$sparql->select("?name");

//new pattern
$sparql->new_ptrn("?x foaf:name ?name");

//order information, true specifies descending, 
//false or nothing provided will be treated as ascending
$sparql->order("?emp");

//setting limit
$sparql->limit(10);

//setting offset
$sparql->offset(5);

//generating query
$query = $sparql->query();

Result OFFSET

Back to method list

Method nameoffset($off)
DescriptionOffset result by specified positions
Input parameters

int $off - number of rows to offset

Example usage
//adding prefixes
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");

//selecting node
$sparql->select("?name");

//new pattern
$sparql->new_ptrn("?x foaf:name ?name");

//order information, true specifies descending, 
//false or nothing provided will be treated as ascending
$sparql->order("?emp");

//setting limit
$sparql->limit(10);

//setting offset
$sparql->offset(5);

//generating query
$query = $sparql->query();

ORDER result

Back to method list

Method nameorder($ord, $desc = false)
DescriptionOrder result by specifyied node
Input parameters

string $ord - node by which to order result

boolean $desc - boolean to order descending. If true, descending order will be used, if false, ascending order will be used

Example usage
//adding prefixes
$sparql->prefix("", "http://example.org/ns#");
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
$sparql->prefix("xsd", "http://www.w3.org/2001/XMLSchema#");

//selecting node
$sparql->select("?name");

//new pattern
$sparql->new_ptrn("?x foaf:name ?name ; :empId ?emp");

//order information, true specifies descending, 
//false or nothing provided will be treated as ascending
$sparql->order("?emp", true);

//generating query
$query = $sparql->query();

Build query

Back to method list

Method namequery()
DescriptionReturn query using all specified parameters and empty everything that was inputted, so new query could be built from scratch
Example usage
//defining prefix
$sparql->prefix("foaf", "http://xmlns.com/foaf/0.1/");
//adding what to select
$sparql->select("?name");
$sparql->select("?mbox");

//creating patterns with full graph
$sparql->new_ptrn("?x foaf:name ?name .");
//creating empty pattern,
$pat = $sparql->new_ptrn("");
//adding node after pattern creation
//patterns are interpreted as string, so we may add 
//multiple patterns as one pattern, but they need to be in one clause
// or add nodes one by one, which will form pattern string
$sparql->add_ptrn($pat, "?x");
$sparql->add_ptrn($pat, "foaf:mbox ?mbox .");

//no need to add patterns to where clause, all unused 
//patterns will automatically get to where clause if union wasn't used
//if union was used, then new union will be created 
//and all unused patterns will go there

//generating query
$query = $sparql->query();
Example output
PREFIX foaf: 
SELECT  ?name ?mbox 
WHERE {
?x foaf:name ?name . 
 ?x foaf:mbox ?mbox . 
}

Possible error messages

List of all errors and meanings

Error textMeaningSolution
Incorrect select type specifiedYou specified select type that oesn't existUse only REDUCED or DISTINCT
Can't add to specified pattern, because it doesn't existYou provided non existing pattern identifierCreate new pattern using new_ptrn method
Can't add to where clause, because specified pattern does not existYou provided non existing pattern identifierCreate newpattern using new_ptrn method
Specified optional clause does not existYou provided non existing optional clause identifierDo not povide optional clause identifier to crete new optional clause
Can't add to optional clause because specified pattern does not existYou provided non existing pattern identifierCreate new pattern using new_ptrn method
Can't add to GRAPH because, specified pattern does not existYou provided non existing pattern identifierCreate new pattern using new_ptrn method
Can't add to union head, because specified pattern does not existYou provided non existing pattern identifierCreate new pattern using new_ptrn method
Can't add to union clause, because specified pattern does not existYou provided non existing pattern identifierCreate new pattern using new_ptrn method
Specified union clause does not existYou provided non existing union clause identifierDo not provide union clause identifier to create new union clause
Limit must be positive numberYou provided value that equal or is less zen zeroProvide nubmer then is bigger than zero

Latest changes

None for now

Rate us

Like our script? Rate it at PHP > Hot Scripts

Scripts.com
RATE ME!

Try it out and Rate on PHPclasses.org

Support

PHP classes support forum or comments below

Awards

Sparql Query Builder was nominated to Innovation Award and achieved 10th place, thanks everyone for support


You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus