Search notes:

Querying the Wikidata SPARQL endpoint with PHP

The following PHP snippet tries to demonstrate how PHP's cURL library can be used to query the Wikidata endpoint with a SPARQL query.
<?php

    $query = '
    select ?lifeExpectancy {
       wd:Q39 wdt:P2250 ?lifeExpectancy .
    }
   ';

   $headers = Array(
    # "Content-Type: application/json",
      "Accept: application/sparql-results+json",
   );

   $url         = 'https://query.wikidata.org/sparql';

   $queryFields = ['query' => $query ];
   $postFields  = http_build_query($queryFields);

   $req         = curl_init();

   curl_setopt($req, CURLOPT_URL           , $url);
 # curl_setopt($req, CURLOPT_POST          , true);                    # 
   curl_setopt($req, CURLOPT_POSTFIELDS    , $postFields);             # Implicitely set by CURLOPT_POSTFIELDS
   curl_setopt($req, CURLOPT_USERAGENT     ,'Renes wikidata querier'); # Prevent HTTPS Status 403
   curl_setopt($req, CURLOPT_HTTPHEADER    , $headers);
   curl_setopt($req, CURLOPT_RETURNTRANSFER, true);                    # Let curl_exec return the content rather than printing it to stdout?

   $result = curl_exec($req);
   print($result);
?>
Github repository about-php, path: /curl/wikidata-SPARQL.php

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1759406249, '216.73.216.42', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/web/php/snippets/cURL/wikidata-SPARQL(65): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78