Social Media post using AI model through API calls

Social Media post by using API call to AI Model

Instruction: Create a ~1500-character Google My Business post from this URL: {URL}.

Audience: beginners/intermediate devs.

Focus: Explain ONE core outcome, include 1 tiny code line (no long blocks), and end BEFORE 1500 chars.

Tone: clear, helpful, no hype. Avoid keyword stuffing.

CTA: “Read the full tutorial: {URL}


AI-Powered Social Media Posts Using PHP | Plus2Net Tutorial

Generate Social Media Prompt with PHP & Gemini API

This script is divided into two parts for better clarity and modularity.
In Part I, we define a list of technical topics (keywords), randomly select one, and insert it into a well-crafted prompt template using str_ireplace(). This prepares a complete prompt that could be sent to an AI model for content generation.

In Part II, the script connects to Google’s Gemini API using a secure API key. It sends the generated prompt to the model and retrieves the AI-generated social media content in response.

This two-step approach makes it easy to reuse or test the prompt independently before invoking the API.

<?php
/**
 * Practical use of str_ireplace():
 * Pick a random keyword from an array, inject into a prompt paragraph,
 * and (optionally) call your AI API to generate a social media post.
 */

// 1) Your keyword pool (expand as needed)
$keywords = [
    'Tkinter Treeview insert',
    'tkcalendar DateEntry',
    'PHP array unpacking',
    'MySQL BETWEEN query',
    'Regex with preg_match',
    'Python file handling',
];

// 2) Prompt paragraph template
$promptTemplate = <<<TXT
Create a ~1500-character Google My Business post on: {KEYWORD}.

Audience: beginners/intermediate devs.
Focus: Explain ONE core outcome, include 1 tiny code line (no long blocks), and end BEFORE 1500 chars.
Tone: clear, helpful, no hype. Avoid keyword stuffing.
TXT;

// 3) Pick a random keyword
if (empty($keywords)) {
    die("No keywords available.\n");
}
$randomKey = array_rand($keywords);
$selected  = $keywords[$randomKey];

// 4) Replace placeholder with keyword
$replacedCount = 0;
$finalPrompt = str_ireplace('{KEYWORD}', $selected, $promptTemplate, $replacedCount);

// 5) Output prompt
header('Content-Type: text/plain; charset=UTF-8');
echo "Selected keyword: {$selected}\n";
echo "Occurrences replaced: {$replacedCount}\n\n";
echo "---- PROMPT TO SEND ----\n";
echo $finalPrompt . "\n";

// -------------------- Optional Gemini API Call ( Part - II )--------------------

require 'ai_v1/settings.php'; // defines $GOOGLE_API_KEY
$MODEL = 'gemini-2.5-flash';

if (!$GOOGLE_API_KEY) {
    exit("\n[Note] Skipping API call: set GEMINI_API_KEY env var.\n");
}

$url = "https://generativelanguage.googleapis.com/v1beta/models/{$MODEL}:generateContent";
$payload = [
    "contents" => [[ "parts" => [["text" => $finalPrompt]] ]]
];

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        "x-goog-api-key: $GOOGLE_API_KEY",
    ],
    CURLOPT_POSTFIELDS     => json_encode($payload),
    CURLOPT_TIMEOUT        => 60,
]);
$res = curl_exec($ch);

if (curl_errno($ch)) {
    echo "\nAPI error: " . curl_error($ch) . "\n";
} else {
    $data = json_decode($res, true);
    $text = $data['candidates'][0]['content']['parts'][0]['text'] ?? null;
    echo "\n---- GENERATED SOCIAL POST ----\n";
    echo $text ? $text : "No text returned. Raw response:\n" . $res;
}
curl_close($ch);
?>

Enhancements & Extensions: AI-Generated Social Media Posts (PHP + Gemini)

Use the following concepts and examples to expand this tutorial further — targeting different platforms, post formats, and creative ideas. Build your own workflows that generate unique posts for LinkedIn, Twitter, Instagram, or Google Business directly from URLs or content snippets.


1) Platform Templates & Use-Cases

Provide short, tuned templates per platform + audience. Inject {URL}, {AUDIENCE}, {TONE}, {CTA} as variables.

Template snippets
// Twitter/X (≤280 chars)
"Write a concise post (≤250 chars) for {AUDIENCE} about {URL}. Tone: {TONE}.
End with 1 hashtag and a short CTA."

// LinkedIn (~600–1200 chars)
"Write a clear LinkedIn post for {AUDIENCE} summarizing {URL}.
Focus on one outcome, add 1 question to invite comments, end with a soft CTA."

// Instagram caption
"Create an IG caption (≤150 words) based on {URL}. Conversational.
One key benefit, one micro-tip, 3 relevant hashtags, 1 CTA."

// Google Business Profile (~1200–1500 chars)
"Create a GBP post from {URL}. Audience: beginners/intermediate devs.
One core outcome, include 1 tiny code line (no long blocks), end with CTA link."

2) URL-List Driven Content Extraction

Collect URLs (CSV/array), fetch basic context (title, meta description, first 120–200 words), then feed to the model.

Minimal PHP extractor + random URL picker
<?php
$urls = [
  "https://example.com/post-1",
  "https://example.com/post-2",
  "https://example.com/post-3"
];

function fetch_context($url) {
  $html = @file_get_contents($url);
  if(!$html) return ["title"=>"", "desc"=>"", "snippet"=>""];
  libxml_use_internal_errors(true);
  $dom = new DOMDocument();
  $dom->loadHTML($html);
  $xpath = new DOMXPath($dom);

  $title = $xpath->evaluate('string(//title)');
  $desc  = $xpath->evaluate('string(//meta[@name="description"]/@content)');
  $text  = trim($xpath->evaluate('string(//body)'));
  $snippet = mb_substr(preg_replace("/\s+/", " ", $text), 0, 600);

  return ["title"=>$title, "desc"=>$desc, "snippet"=>$snippet];
}

$chosen = $urls[array_rand($urls)];
$ctx = fetch_context($chosen);

// Build prompt (example: LinkedIn)
$prompt = "Create a LinkedIn post for intermediate devs. Base it on: {$chosen}\n".
          "Title: {$ctx['title']}\nMeta: {$ctx['desc']}\nSnippet: {$ctx['snippet']}\n".
          "One key outcome, 1 question, end with CTA linking to {$chosen}.";
?>

Tip: Cache fetch_context() results (filesystem/Redis) to save API calls while iterating.

3) Prompt Engineering Tips

  • Specify audience, outcome, length, and CTA explicitly.
  • Ask for 1–2 variants to enable A/B tests.
  • Checklist: mentions URL? one core benefit? avoids fluff? has CTA?
Weak → Strong prompt example
// Weak
"Write a post about this link {URL}."

// Strong
"Write a {PLATFORM} post for {AUDIENCE} based on {URL}. Highlight ONE benefit,
keep it under {LIMIT}. Include 1 question for engagement and end with CTA:
<a href='{URL}'>Read more</a>."

4) Code Structure & Best Practices

  • Split config, helpers, API client, and UI files.
  • Use environment variables for API keys.
  • Centralize error handling + logging.
  • Add simple response cache to avoid re-billing.
Mini structure
/app
  /config.php         // env, model, limits
  /helpers.php        // fetch_context(), sanitize(), cache_get/set()
  /ai_client.php      // call_gemini($prompt)
  /render.php         // HTML render + UI
  /publishers/*.php   // X, LinkedIn, GBP schedulers

5) UI / Web Form Example

Let a user paste URLs or upload CSV, pick platform + tone, then generate.

Simple form
<form method="post">
  <textarea name="urls" placeholder="One URL per line" required></textarea>
  <select name="platform">
    <option>Twitter</option><option>LinkedIn</option>
    <option>Instagram</option><option>GBP</option>
  </select>
  <input name="tone" placeholder="Tone e.g., helpful, witty">
  <button>Generate</button>
</form>

6) Post-Processing & Review Workflow

  • Auto-checks: length, presence of URL, presence of CTA, banned words.
  • Human review: editable textarea + Approve/Revise buttons.
  • Store approved posts (status, author, date) for audit.

7) Publishing & Scheduling

After approval, queue for APIs (X, LinkedIn) or use schedulers (Buffer/Hootsuite). Respect rate limits; keep retry logic.

9) Metrics & A/B Testing

  • Track: clicks, likes, comments, saves, CTR.
  • A/B: two variants per URL/platform. Tag as A or B; compare CTR.
  • Log results to DB; show weekly leaderboard of best prompts.

10) Security, Cost & Ethics

  • Store API keys outside web-root; use env vars.
  • Show token/cost estimate per call; add daily budget caps.
  • Respect site ToS when scraping; credit sources in posts.

11) Multimedia: Text + Image Flow

  1. Summarise URL → extract 3 concepts.
  2. Generate image prompt for 1 key concept.
  3. Create image (or pick from library) → attach to post text.

12) Internationalisation (Multi-Language)

Add a lang selector; pass language + locale to the prompt; enforce local character conventions.

Prompt add-on
"Write in {LANGUAGE_CODE}. Use local punctuation and spacing rules."

13) Composer Package (Optional)

  • Create a small library: plus2net/ai-social-posts.
  • Expose: fetchContext(), buildPrompt(), callModel(), validatePost(), publish().
  • Ship stubs for platform publishers.

14) CMS / WordPress Integration

Generate a post when a blog is published. Add meta-box to preview/edit before scheduling.

WP hook sketch
add_action('publish_post', function($post_id){
  $url = get_permalink($post_id);
  $ctx = fetch_context($url);
  $prompt = build_prompt($url, $ctx, 'LinkedIn');
  $post = call_model($prompt);
  update_post_meta($post_id, '_generated_social_post', $post);
});

15) Troubleshooting & FAQ

Common issues
  • Post too long: tighten prompt; add explicit char cap; trim on output.
  • Generic output: inject concrete context (title, meta, snippet, target audience).
  • Empty fetch: fallback to OpenGraph tags; show manual paste field.
  • Rate limits: add exponential backoff + queue.

16) Quick Plan (Priorities)

  1. Implement URL extraction + prompt injection.
  2. Add platform templates + tone selector.
  3. Build review UI (approve/revise) + caching.
  4. Ship examples gallery + basic analytics (CTR).
  5. Add scheduling + minimal WP hook.

Bonus: One-File Demo (Pick random URL → Generate)

<?php
require __DIR__.'/vendor/autoload.php'; // if needed

$urls = array_filter(array_map('trim', explode("\n", $_POST['urls'] ?? '')));
$platform = $_POST['platform'] ?? 'LinkedIn';
$tone = $_POST['tone'] ?? 'helpful';

function fetch_context($url){ /* same as above (trimmed for brevity) */ }

function validate_post($text, $url){
  return [
    'has_url' => str_contains($text, $url),
    'has_cta' => preg_match('/read|learn|try|start|join|visit/i', $text) === 1,
    'len_ok'  => mb_strlen($text) < 1200
  ];
}

if($_SERVER['REQUEST_METHOD']==='POST' && $urls){
  $picked = $urls[array_rand($urls)];
  $ctx = fetch_context($picked);
  $prompt = "Platform: {$platform}\nTone: {$tone}\nURL: {$picked}\n".
            "Title: {$ctx['title']}\nMeta: {$ctx['desc']}\n".
            "Snippet: {$ctx['snippet']}\n".
            "Write ONE {$platform} post with 1 outcome and a CTA linking to {$picked}.";
  $generated = call_gemini($prompt); // your existing client
  $check = validate_post($generated, $picked);
}
?>

All PHP Scripts Gemini API AI Prompt Generator
Subhendu Mohapatra — author at plus2net
Subhendu Mohapatra

Author

🎥 Join me live on YouTube

Passionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer