Skip to content

Instantly share code, notes, and snippets.

@gubatron
Last active September 27, 2025 11:28
Show Gist options
  • Save gubatron/f7526ace5ebf915981c535568e0549e4 to your computer and use it in GitHub Desktop.
Save gubatron/f7526ace5ebf915981c535568e0549e4 to your computer and use it in GitHub Desktop.
PHP function to return HTML to embed a tweet like publish.x.com would
<?php
/**
* Returns HTML to embed a tweet like publish.x.com would
*/
function embed_tweet_html(string $tweet_url) : ?string {
// Encode the tweet URL for the query parameter
$encoded_url = urlencode($tweet_url);
// Construct the oEmbed API URL
$api_url = "https://publish.twitter.com/oembed?url=" . $encoded_url;
// Use cURL to make the GET request
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
curl_close($ch);
// Check if the response is valid
if ($response === false) {
return null; // or throw an error
}
// Decode the JSON response
$data = json_decode($response, true);
// Check if 'html' key exists
if (isset($data['html'])) {
return $data['html'];
} else {
return null; // or throw an error
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment