Knowledge Engineering @ CUI

Up to Semantic Web Technologies

Creating web pages from linked data with PHP and SPARQL

The idea is to use PHP to query SPARQL endpoints and generate HTML pages.

There are several PHP libraries to query SPARQL endpoints. Of course they are all either incomplete or buggy or poorly documented or … . Anyway …

1. Creating our first page

1. Create a sub-directory, say linked-data, in your web site directory.

2. Download the ARC2 library from (on into linked-data

2. Decompress the .tar.gz file. It should create a directory called semsol-arc2-ebd59b0 (or something similar). Rename it to semsol

3. In the same directory create test1.php with the following content

  include_once('semsol/ARC2.php'); /* ARC2 static class inclusion */ 
  $dbpconfig = array(
  "remote_store_endpoint" => "",
  $store = ARC2::getRemoteStore($dbpconfig); 
  if ($errs = $store->getErrors()) {
     echo "<h1>getRemoteSotre error<h1>" ;
  $query = '
      PREFIX rdf:      <>
      PREFIX rdfs:     <>
      select distinct ?l ?c 
         where {?c a rdfs:Class. ?c rdfs:label ?l}
      limit 100
  $rows = $store->query($query, 'rows'); /* execute the query */
  if ($errs = $store->getErrors()) {
     echo "Query errors" ;
  /* display the results in an HTML table */
  echo "<table border='1'>" ;
  foreach( $rows as $row ) { /* loop for each returned row */
         print "<tr><td>" .$row['l'] . "</td><td>" . $row['c']. "</td></tr>";
  echo "</table>"

4. In a browser open the URL http://your-site/linked-data/test1.php

The result should look like

Label Property

General structure of a query page

As we can see on the previous example, the php code to query a remote endpoint must proceed as the follows

  1. configure and “open” the endpoint ($config = \ldots ; ARC2::getRemoteStore($config); )
  2. define the query ($query = …)
  3. execute the query ($rows = $store→query($query, 'rows'); )
  4. process (display) the results (foreach $rows as … )

When executed, a query of the form

select ?x1 … ?xn where <condition>

yields a set of rows, each one containing values for the xi's that satisfy the selection condition.

The standard way to process the results is through an iteration

  foreach $rows as $r {
    <do something with $r>

$r is an associative array, with the following contents:

$r['var'] is the value of the query variable ?var.

$r['var type'] is the value type, either 'uri' or 'literal' or 'bnode' (blank node).

$r['var datatype'] is the value datatype if the value is a literal (empty if not a literal or if the datatype is not explicitly specified).

$r[var lang'] is the language of the literal value (empty if not a literal or if the language is not explicitly specified).