How to Integrate Gemini API into Your PHP Projects Using Curl

WBOY
Release: 2024-08-11 16:38:02
Original
805 people have browsed it

Learn how to seamlessly integrate the powerful Gemini Text API into your PHP applications using the versatile Curl library. This comprehensive guide covers step-by-step instructions, code examples, and best practices to help you effectively leverage Gemini's advanced text capabilities. Unlock the potential of AI-driven text processing and enhance your PHP projects today.

Gemini has many options to work with, here I will introduce about how you can use Gemini Text generation API with your PHP project. You can use this script with various platforms such as WordPress, Laravel, CakePHP, CodeIgniter etc.

Let's see the below code ...

<?php
try {

    $apiKey = 'enter-you-gemini-api-key';
    $apiUrl = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent';

    $message = "List top PHP frameworks based on PHP. What are their advantages.";


    $data = json_encode([
        'contents' => [
            [
                'parts' => [
                    [
                        'text' => "$message"
                    ]
                ]
            ]
        ]
    ]);

    $ch = curl_init($apiUrl . '?key=' . $apiKey);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json'
    ]);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $response = curl_exec($ch);
    $responseArray = json_decode($response, true);

    if (isset($responseArray['candidates'][0]['content']['parts'][0]['text'])) {
        $text = $responseArray['candidates'][0]['content']['parts'][0]['text'];
        echo $text;
    } else {
        echo "error";
    }


    curl_close($ch);


} catch (Exception $e) {
    echo $e->getMessage();
}
?>

Copy after login

Output

How to Integrate Gemini API into Your PHP Projects Using Curl

The above is the detailed content of How to Integrate Gemini API into Your PHP Projects Using Curl. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template