1. Go to this page and download the library: Download marcino0o/openai library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
marcino0o / openai example snippets
Openai\OpenAISDK;
use Openai\OpenAIHTTPClient;
use Openai\Chat\Messages;
use Openai\Chat\Message;
$sdk = new OpenAISDK(
new OpenAIHTTPClient(apiKey: getenv('OPENAI_API_KEY'))
);
$response = $sdk->createChatCompletion(
new Messages(
Message::fromUser('Tell me a funny programming joke!')
)
);
echo $response->content();
$response = $sdk->createChatCompletion(
new Messages(
Message::fromUser('Explain recursion in a short PHP example.')
)
);
echo $response->choices->current()?->message->content;
$response = $sdk->createChatCompletion(
new Messages(
Message::fromSystem('You are a concise assistant replying in English.'),
Message::fromUser('Summarize monads in 2 sentences.')
)
);
$response = $sdk->createChatCompletion(
new Messages(
Message::fromUser('Summarize this in one paragraph: ...')
),
model: \Openai\Model::tryFromModelString(getenv('OPENAI_MODEL') ?: 'gpt-4.1-mini')
);
use Openai\Chat\PresencePenalty;
use Openai\Chat\ReasoningEffort;
use Openai\Chat\TopP;
$response = $sdk->createChatCompletion(
messages: new Messages(
Message::fromSystem('You are a concise assistant.'),
Message::fromUser('Summarize this article in 5 bullet points.')
),
model: \Openai\Model::GPT_4_1,
presencePenalty: PresencePenalty::tryFrom(0.2),
topP: TopP::tryFrom(0.95),
maxCompletionTokens: 400,
stop: ['<END>'],
reasoningEffort: ReasoningEffort::MEDIUM,
);
$response = $sdk->createImage(prompt: \Openai\Prompt::fromString('A futuristic city skyline at sunset'));
file_put_contents('city.png', base64_decode($response->images[0]->base64));
$response = $sdk->createModeration(input: 'This text contains hate speech.');
if ($response->moderationResult->flagged) {
echo 'Content flagged for moderation';
}