This turorial is part of the RAP - Rdf API for PHP documentation.
Tobias Gauss <tobias.gauss@web.de>
June 2006
RAP's SPARQL client provides the functionality to execute a SPARQL query against a SPARQL server and retrieve the result as an array which contains the variables an their bindings.
First of all create a new SparqlClient object:
|
This line creates a new SparqlClient object $client
which is linked with the SPARQL Service http://www.exampleSparqlService.net:2020/example
.
Then create a ClientQuery object:
|
The ClientQuery object provides three methods:
|
To add a Default Graph name to the ClientQuery object,
|
To add a Named Graph name to the ClientQuery object. And
|
to add a query string to the ClientQuery object.
Now You can execute the query by calling the method query($query):
|
Now the query is executed and result ist returned. The result format is either a MemModel if the query is a CONSTRUCT query or an array which contains the variables and their bindings. You can also change the result format to SPARQL Query Results XML Format by calling the method:
|
To clearify the usage here is a simple example. We start with including the RAP package and creating a SPARQL client linked to a SPARQL service:
|
Once the client has been created, we can perform our first query which will be: "Find the full name of all employees".
So, we create a variable $querystring
and assign the corresponding query string:
|
To execute the query, we create a new ClientQuery object:
|
The result of the query is an two dimension array of variable bindings ($result[]['?varname'] ). The values of these variables are RAP objects (Resource
,
Literal
or BlankNode
) or an empty string if the variable is unbound . The following code loops over the result set and prints out all bindings of the variable ?fullName
.
|
Another, even more convenient way to display the results of a query is to use the writeQueryResultAsHtmlTable()
method of the SPARQL engine. All we have to do is to pass the query result to this method:
|
Which will result in the following output in the browser window:
No. | ?fullName |
1. | Literal: Bill Parker |
2. | Literal: George Simpson |
3. | Literal: Monica Murphy |
If we want the engine to return the query result in SPARQL Query Results XML Format, we have to add 'xml' as second parameter to the function call:
|
Now the variable $result2 contains a string which represents the results in SPARQL Query Results XML Format:
<?xml version="1.0"?> |
The result of an ASK query is a boolean value.
The result of a CONSTRUCT query is a MemModel:
|
For more SPARQL query examples please refer to the W3C SPARQL Working Draft.