You are here

function querypath_examples_show_sparql_lookup in QueryPath 7.2

Same name and namespace in other branches
  1. 6 querypath_examples.module \querypath_examples_show_sparql_lookup()
  2. 7.3 querypath_examples.module \querypath_examples_show_sparql_lookup()
1 call to querypath_examples_show_sparql_lookup()
querypath_examples_show_sparql_form_validate in ./querypath_examples.module

File

./querypath_examples.module, line 348
The main file for querypath_examples.

Code

function querypath_examples_show_sparql_lookup($term) {

  // URL to DB Pedia's SPARQL endpoint.
  $base_url = 'http://dbpedia.org/sparql';

  // The SPARQL query to run.
  $query = '
    PREFIX foaf: <http://xmlns.com/foaf/0.1/>
    PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
    SELECT ?uri ?name ?label
    WHERE {
      ?uri foaf:name ?name .
      ?uri rdfs:label ?label
      FILTER (?name = "%s")
      FILTER (lang(?label) = "en")
    }
  ';
  $sparql = sprintf($query, $term);

  // We first set up the parameters that will be sent.
  $params = array(
    'query' => $sparql,
    'format' => 'application/sparql-results+xml',
  );

  // DB Pedia wants a GET query, so we create one.
  $data = http_build_query($params);
  $url = $base_url . '?' . $data;

  // Next, we simply retrieve, parse, and output the contents.
  $qp = qp($url, 'head');

  // Get the headers from the resulting XML.
  $headers = array();
  foreach ($qp
    ->children('variable') as $col) {
    $headers[] = $col
      ->attr('name');
  }

  // Get rows of data from result.
  $rows = array();
  $col_count = count($headers);
  foreach ($qp
    ->top()
    ->find('results>result') as $row) {
    $cols = array();
    $row
      ->children();
    for ($i = 0; $i < $col_count; ++$i) {
      $item = $row
        ->branch()
        ->eq($i);
      if ($item
        ->branch()
        ->children('uri')
        ->size() == 1) {
        $txt = $item
          ->text();
        $cols[$i] = querypath_examples_format_ld_link($txt, $txt);
      }
      else {
        $cols[$i] = $item
          ->text();
      }
    }
    $rows[] = $cols;
  }
  $caption = t('SPARQL Query results from DBPedia');
  $out = t('Results of issuing @url the following query: ', array(
    '@url' => $base_url,
  )) . '<pre>' . $sparql . '</pre>';
  $out .= theme('table', $headers, $rows, array(), $caption);
  $out .= htmlentities($qp
    ->top()
    ->xml());
  return $out;
}