JokeAPI PHP
April 18, 2025 ยท View on GitHub
A PHP wrapper for the JokeAPI.
Installation
Currently, this package is not available on Packagist. To use it, simply clone this repository:
git clone https://github.com/yourusername/jokeapi-php.git
Usage
<?php
require_once 'path/to/JokeAPI/JokeClient.php';
use JokeAPI\JokeClient;
use JokeAPI\JokeConstants;
// Create a new JokeClient
$client = new JokeClient();
// Get a random joke
$joke = $client->fetch();
// Print the joke
if ($joke['type'] === 'single') {
echo $joke['joke'];
} else {
echo "Setup: " . $joke['setup'] . "\n";
echo "Delivery: " . $joke['delivery'];
}
Features
The JokeAPI PHP client supports all the features of the JokeAPI:
- Multiple categories
- Blacklist flags
- Different formats (JSON, XML)
- Joke types (single, twopart)
- Search functionality
- Specific joke IDs
- Multiple languages
- Safe mode
Methods
categories(array $categories)
Set the categories for the jokes.
$client->categories([
JokeConstants::CATEGORY_PROGRAMMING,
JokeConstants::CATEGORY_MISC
]);
Available categories:
CATEGORY_ANY(default)CATEGORY_MISCCATEGORY_PROGRAMMINGCATEGORY_DARKCATEGORY_PUNCATEGORY_SPOOKYCATEGORY_CHRISTMAS
blacklist(array $flags)
Set blacklist flags to filter jokes.
$client->blacklist([
JokeConstants::FLAG_NSFW,
JokeConstants::FLAG_RELIGIOUS
]);
Available flags:
FLAG_NSFWFLAG_RELIGIOUSFLAG_POLITICALFLAG_RACISTFLAG_SEXISTFLAG_EXPLICIT
format(string $format)
Set the response format (json or xml).
$client->format('xml');
type(string $type)
Set the joke type (single or twopart).
$client->type(JokeConstants::TYPE_SINGLE);
Available types:
TYPE_SINGLETYPE_TWOPART
search(string $searchString)
Search for jokes containing the specified string.
$client->search('programmer');
id(int $id)
Get a joke by ID.
$client->id(42);
language(string $language)
Set the language for the jokes.
$client->language(JokeConstants::LANG_GERMAN);
Available languages:
LANG_ENGLISH(default)LANG_CZECHLANG_GERMANLANG_SPANISHLANG_FRENCHLANG_PORTUGUESE
safe(bool $safe = true)
Enable safe mode (excludes nsfw jokes).
$client->safe();
fetch()
Fetch a joke from the API.
$joke = $client->fetch();
Chaining
All methods (except fetch()) return the client instance for method chaining:
$joke = $client
->categories([JokeConstants::CATEGORY_PROGRAMMING])
->blacklist([JokeConstants::FLAG_NSFW])
->safe()
->fetch();
License
MIT
Credits
This is a PHP port of the jokeapi Go package by Icelain.