PHP Examples
Code examples for integrating WikiRest with PHP applications.
Installation
Using cURL (built-in) or Guzzle HTTP client:
composer require guzzlehttp/guzzle API Client
Basic client class with cURL
<?php
class WikiRestClient
{
private const BASE_URL = 'https://api.wikirest.com/v1';
private string $apiKey;
public function __construct(string $apiKey)
{
$this->apiKey = $apiKey;
}
public function search(string $query, int $limit = 10): array
{
$params = http_build_query([
'q' => $query,
'limit' => $limit
]);
return $this->request('GET', '/search?' . $params);
}
public function getChunk(string $id): array
{
return $this->request('GET', '/chunk/' . $id);
}
public function getPage(int $pageId, string $format = 'chunks'): array
{
$params = http_build_query(['format' => $format]);
return $this->request('GET', '/page/' . $pageId . '?' . $params);
}
public function getChanges(?string $since = null, int $limit = 100): array
{
$params = ['limit' => $limit];
if ($since) {
$params['since'] = $since;
}
return $this->request('GET', '/changes?' . http_build_query($params));
}
private function request(string $method, string $path): array
{
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => self::BASE_URL . $path,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'X-API-Key: ' . $this->apiKey,
'Accept: application/json'
],
CURLOPT_TIMEOUT => 30
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
throw new Exception('cURL error: ' . curl_error($ch));
}
curl_close($ch);
if ($httpCode >= 400) {
throw new Exception('API error: ' . $response);
}
return json_decode($response, true);
}
} Search
Search Wikipedia
<?php
$client = new WikiRestClient($_ENV['WIKIREST_API_KEY']);
// Basic search
$results = $client->search('quantum computing', 5);
echo "Found {$results['estimatedTotalHits']} results\n";
foreach ($results['hits'] as $hit) {
echo "- {$hit['title']}: " . substr($hit['text'], 0, 100) . "...\n";
} Search with error handling
<?php
function safeSearch(WikiRestClient $client, string $query): array
{
try {
$results = $client->search($query);
return $results['hits'];
} catch (Exception $e) {
error_log("Search failed: " . $e->getMessage());
return [];
}
}
$hits = safeSearch($client, 'artificial intelligence');
foreach ($hits as $hit) {
echo $hit['title'] . "\n";
} Working with Chunks
Get a specific chunk
<?php
$chunk = $client->getChunk('12345_3');
echo "Title: {$chunk['title']}\n";
echo "Section: {$chunk['section']}\n";
echo "Text: {$chunk['text']}\n";
echo "URL: {$chunk['url']}\n"; Process multiple chunks
<?php
$results = $client->search('machine learning', 10);
$chunks = array_map(function ($hit) {
return [
'id' => $hit['id'],
'title' => $hit['title'],
'section' => $hit['section'] ?? '',
'text' => $hit['text'],
'url' => $hit['url']
];
}, $results['hits']);
foreach ($chunks as $chunk) {
echo "Processing: {$chunk['title']} - {$chunk['section']}\n";
} Using Guzzle
Cleaner implementation with Guzzle
<?php
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class WikiRest
{
private Client $client;
public function __construct(string $apiKey)
{
$this->client = new Client([
'base_uri' => 'https://api.wikirest.com/v1/',
'headers' => [
'X-API-Key' => $apiKey,
'Accept' => 'application/json'
],
'timeout' => 30
]);
}
public function search(string $query, int $limit = 10): array
{
try {
$response = $this->client->get('search', [
'query' => ['q' => $query, 'limit' => $limit]
]);
return json_decode($response->getBody(), true);
} catch (GuzzleException $e) {
throw new Exception('Search failed: ' . $e->getMessage());
}
}
public function getChunk(string $id): array
{
$response = $this->client->get('chunk/' . $id);
return json_decode($response->getBody(), true);
}
public function getPage(int $pageId, string $format = 'chunks'): array
{
$response = $this->client->get('page/' . $pageId, [
'query' => ['format' => $format]
]);
return json_decode($response->getBody(), true);
}
}
// Usage
$wiki = new WikiRest($_ENV['WIKIREST_API_KEY']);
$results = $wiki->search('php programming');
foreach ($results['hits'] as $hit) {
echo $hit['title'] . "\n";
} Laravel Integration
Service provider setup
<?php
// config/services.php
return [
// ...
'wikirest' => [
'api_key' => env('WIKIREST_API_KEY'),
],
];
// app/Services/WikiRestService.php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
class WikiRestService
{
private string $apiKey;
private string $baseUrl = 'https://api.wikirest.com/v1';
public function __construct()
{
$this->apiKey = config('services.wikirest.api_key');
}
public function search(string $query, int $limit = 10): array
{
return Cache::remember("wiki_search_{$query}_{$limit}", 3600, function () use ($query, $limit) {
$response = Http::withHeaders([
'X-API-Key' => $this->apiKey
])->get("{$this->baseUrl}/search", [
'q' => $query,
'limit' => $limit
]);
return $response->json();
});
}
public function getPage(int $pageId): array
{
return Cache::remember("wiki_page_{$pageId}", 86400, function () use ($pageId) {
$response = Http::withHeaders([
'X-API-Key' => $this->apiKey
])->get("{$this->baseUrl}/page/{$pageId}");
return $response->json();
});
}
}
// app/Providers/AppServiceProvider.php
public function register()
{
$this->app->singleton(WikiRestService::class);
} Using in a controller
<?php
namespace App\Http\Controllers;
use App\Services\WikiRestService;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function __construct(private WikiRestService $wikiRest) {}
public function index(Request $request)
{
$query = $request->validate(['q' => 'required|string|max:500'])['q'];
$results = $this->wikiRest->search($query);
return view('search.results', [
'query' => $query,
'results' => $results['hits'],
'total' => $results['estimatedTotalHits']
]);
}
public function show(int $pageId)
{
$page = $this->wikiRest->getPage($pageId);
return view('wiki.show', ['page' => $page]);
}
} Artisan command for batch operations
<?php
namespace App\Console\Commands;
use App\Services\WikiRestService;
use Illuminate\Console\Command;
class SyncWikiPages extends Command
{
protected $signature = 'wiki:sync {--page_ids=*}';
protected $description = 'Sync Wikipedia pages to local database';
public function handle(WikiRestService $wikiRest)
{
$pageIds = $this->option('page_ids');
$this->info('Syncing ' . count($pageIds) . ' pages...');
$bar = $this->output->createProgressBar(count($pageIds));
foreach ($pageIds as $pageId) {
try {
$page = $wikiRest->getPage((int) $pageId);
\App\Models\WikiArticle::updateOrCreate(
['page_id' => $pageId],
[
'title' => $page['title'],
'content' => $page['text'] ?? '',
'url' => $page['url'],
'synced_at' => now()
]
);
} catch (\Exception $e) {
$this->error("Failed to sync page {$pageId}: {$e->getMessage()}");
}
$bar->advance();
}
$bar->finish();
$this->newLine();
$this->info('Sync complete!');
}
}