Automation is growing more vital in the modern era of content creation. AI Content Writer is one of the most powerful content generation tools available today, with OpenAI’s ChatGPT standing out as a popular choice to generate human-like writing. AI may save you a lot of time while improving the quality of your blog posts, articles, and product descriptions.
In this tutorial, we’ll walk you through the steps of building your own AI content writer with PHP and the OpenAI ChatGPT API.
Get a professionally designed and developed website tailored to your needs.
As an experienced website developer based in Delhi NCR, I offer customized solutions to build responsive, SEO-friendly, and user-friendly websites. Whether it’s for a personal blog, business site, or e-commerce store, I ensure your online presence stands out.
What is ChatGPT?
ChatGPT built by openAI, is a strong language model that creates text that appears human and natural. It is trained on a large amount of data from many sources, allowing it to generate content on a wide range of themes, tones, and styles.
For example, if you require an article on a specific topic, you can simply tell ChatGPT, ‘Write a 500-word essay about AI in 2025,’ and it will generate content according to your specifications. This makes it a great tool for content creators who want to save time while improving their work.
Setting Up the OpenAI API
Before diving into the development, the first step is to set up the OpenAI API. Here’s how:
- Create an OpenAI Account: Go to OpenAI and create an account.
- Get Your API Key: Once you’ve created an account and logged in, Create your project and navigate to the API section to generate an API key. This key will allow your PHP application to communicate with OpenAI’s servers.
Generate API Key
Now copy and save this key in a safe place for future use in the project.
Create a Frontend User Input Form
The first part of your application will be a simple HTML form where users can input the following details:
- Topic: The subject for which they need content.
- Tone: The tone of the article (formal, casual, etc.).
- Word Count: The desired length of the article.
Copy and Paste HTML code for the frontend:
PHP (index.php)
AI Content Writer | Tutorials Website
AI Content Writer
Suggested Read: Best 20 ChatGPT Prompts for All Your Work Needs
Backend: PHP Script for OpenAI Integration
Run below command on terminal. Note: Composer should be installed on your local system.
composer require erusev/parsedown
You will get vendor folder which we will use or include in the next code for html formatting.
Now that we have the frontend in place, let’s focus on the backend. The openAI.php script handles the interaction between your application and OpenAI’s API.
'system', 'content' => 'You are a professional content writer.'],
['role' => 'user', 'content' => "Write a {$tone} article about '{$topic}' in approximately {$wordCount} words."]
];
// Prepare the OpenAI API request payload
$data = [
'model' => 'gpt-4', // You can change to a different model if required
'messages' => $messages,
'max_tokens' => $wordCount * 4,
'temperature' => 0.7,
'stream' => true, // Enable streaming
];
// Initialize the cURL session
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
]);
$content = ''; // Initialize an empty string to accumulate the content
// Handle the stream of data
curl_setopt($ch, CURLOPT_WRITEFUNCTION, function ($ch, $chunk) use (&$content, $Parsedown) {
$lines = explode("\n", $chunk);
foreach ($lines as $line) {
$line = trim($line);
if (empty($line) || strpos($line, 'data:') !== 0) continue;
$data = json_decode(substr($line, 5), true);
if (isset($data['choices'][0]['delta']['content'])) {
$content .= $data['choices'][0]['delta']['content']; // Accumulate content
// Once you have accumulated the content, convert it from Markdown to HTML
$htmlContent = $Parsedown->text($content); // Convert to HTML
// Output the converted HTML content
echo "data: " . json_encode($htmlContent, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n\n";
ob_flush();
flush();
}
}
return strlen($chunk);
});
// Execute the cURL request
curl_exec($ch);
// Close the cURL connection
curl_close($ch);
// Finalize the stream by sending a [DONE] message
echo "event: close\n";
echo "data: [DONE]\n\n";
ob_flush();
flush();
exit;
}
?>
Are you want to get implementation help, or modify or extend the functionality?
A Tutorialswebsite Expert can do it for you.
Stream Data to Frontend in Real-Time
Here, I’m sending real-time AI-generated content to the user interface via the Server-Sent Events (SSE) method. This enables you to see the article in progress. SSE ensures that content is streamed piece by piece as the model generates it, providing a more seamless user experience.
Conclusion
Building an AI content writer using PHP and OpenAI’s ChatGPT API can save time while producing high-quality, human-like content. This AI tool is easy to integrate into any website or application thanks to its simple user interface, real-time streaming, and minimal backend code.
Also Read: Create Dynamic Image Slider Using PHP and MySQL
Whether you’re creating blogs, articles, or marketing copy, an AI content writer can help you improve your workflow and create more interesting material.
Thanks for reading 🙏, I hope you found How to Create Your Own AI Content Writer in PHP with the ChatGPT API tutorial helpful for your project. Keep learning! If you face any problems – I am here to solve your problems.
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co
