Last active
September 27, 2025 11:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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