I created a wordpress plugin with a add_shortcode filter that sends an api call to our system and retrieves documents from the server. However, I noticed that it fires even in the Admin area while I am editing a post or a page. So as I type the value inside the shortcode, it continuously communicates with the server.
How do I stop the shortcode from firing the api call function unless it was published in the post/page?
Edit- Adding more info
The comments below are putting me on the right track, so I want to add more info for you guys.
I am using the WordPress Boilerplate. I added the add_shortcode filter to the plugin library and I register the add_shortcode in the define_public_hook:
$this->loader->add_shortcode( 'my_plugin', $plugin_public, 'my_shortcode', 10, 2 );
then in my-plugin-public-display.php I add the functions (I'll abbreviate it...):
public function api_get_as_json( $controller, $slug, $action, $params, $endpoint ) {
if ( null == $params ) {
$params = array();
}
// Create URL with params
$url = $endpoint . $controller . $slug . $action . '?' . http_build_query($params);
// echo $url;
// Use curl to make the query
$ch = curl_init();
curl_setopt_array(
$ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true
)
);
$output = curl_exec($ch);
// Decode output into an array
$json_data = json_decode( $output, true );
curl_close( $ch );
return $json_data;
}
/**
* Shortcodes
*
* #since 1.0.0
*/
public function my_shortcode( $atts ) {
//turn on output buffering to capture script output
ob_start();
// Get attributes from shortcode
$attributes = shortcode_atts( array(
...
), $atts, 'my_plugin' );
$my_array = //getting the array attributes here...
/* Send API calls to WhoTeaches, get profile and Packages */
$result = $this->api_get_as_json('controller/', null, 'action', $my_array, $host . "domain.com/api/v1/");
// Load the view
include (plugin_dir_path( dirname( __FILE__ ) ) . 'public/partials/my-plugin-public-display.php');
// Get content from buffer and return it
$output = ob_get_clean();
return $output;
// Clear the buffer
ob_end_flush();
}
Do I need to add or edit something here?
Related
I hope I am not expecting too much. Any help would be extremely useful for me, because I am stuck for days now.
I created a relatively simple wordpress plugin in php.
What is the plugin supposed to do ?
-The plugin is supposed to communicate with external api and import product data in json file.
Import is started by pressing "start import" button that is created by pluin in the wordpress menu - import products.
Example request:
curl -X GET
-H 'X-Api-Key: [api-key]'
https://example.com/products/[PRODUCT ID]
[PRODUCT ID] is supposed to range from 1 to 10000
Plugin receives json file with product feed for every single request - every single [PRODUCT ID]
Plugin creates a woocommerce product and attaches imported information.
Does the plugin work ?
Yes and no, It imports first 100 products (in about 1min) correctly and then it just stops, sometimes resulting in error related to the request taking too much time to finish.
I know that the plugin doesn't work because the import script is executed in the browser and gets timed out.
I also know that I should do this process in the background, split it into batches and queue execution. The thing is I tried many ways to do so but failed miserably.
I have composer and action scheduler installed.
Unfortunately everytime I try to split this into batches, use action scheduler It just doesn't work or imports first product and stops.
I know that I'm dealing with large amount of products, I don't have error handling, checking if imported product exists etc, but I really have to run this import once
so there is no need to make this plugin very refined. This has to run, import products and I can get rid of it.
I do have wp debug on, so my attepmts on using action scheduler didn't create any errors or fatal errors, but it just didn't work properly.
I have 1500MB Ram available, this is shared hosting server, I/O 1MB, 60 available processes, 88000/600000 Inodes used, 5/200GB disc space used.
I increased php maxExecutionTime to 3000, memorylimit 1536M, maxInputTime 3000, but that didn't change anything.
I'm attaching my working code below. This is the version without my poor attemts on using action scheduler, splitting it into batches and running it in the backgroud.
I feel like this is going to be easier to read.
This code below runs in the web browser and works, but gets timed out.
I will be extremely grateful for any help with running it in the background.
Is it possible to just run this script from SSH linux terminal so it doesn't get timed out ?
`
<?php
/**
* Plugin Name: Product Importer
* Description: Imports products from an external API
* Version: 1.0
* Author: me
* Author URI: http://www.example.com
*/
// Include the Autoscheduler library
require_once '/home/user/vendor/woocommerce/action-scheduler/action-scheduler.php';
add_action('admin_menu', 'add_import_button');
function add_import_button() {
add_menu_page('Import Products', 'Import Products', 'manage_options', 'import_products', 'import_products_page');
}
function import_products_page() {
echo '<h1>Import Products</h1>';
echo '<form method="post">';
echo '<input type="submit" name="start_import" value="Start Import">';
echo '</form>';
if (isset($_POST['start_import'])) {
import_function();
}
}
function import_function() {
$product_id = 1;
while($product_id < 10000){
$product_id++;
$api_key = 'my-api-key';
$headers = array(
'X-Api-Key: ' . $api_key,
);
$url = 'https://example.com/products/';
$product_url = $url . $product_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $product_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$product_data = json_decode($response, true);
// post array etc
// Set other product data as required.
}
}
}
`
One of the ways to solve this issue is using recursion where the code can run in the background. Take a look at the example below
require_once '/home/user/vendor/woocommerce/action-scheduler/action-scheduler.php';
add_action('admin_menu', 'add_import_button');
function add_import_button() {
add_menu_page('Import Products', 'Import Products', 'manage_options', 'import_products', 'import_products_page');
}
function import_products_page() {
echo '<h1>Import Products</h1>';
echo '<form method="post">';
echo '<input type="hidden" name="product_id" value="1">'; // optional
echo '<input type="submit" name="start_import" value="Start Import">';
echo '</form>';
if (isset($_POST['start_import'])) {
import_function();
}
}
// AJAX function
add_action( 'wp_ajax_nopriv_import_function', 'import_function' );
add_action( 'wp_ajax_import_function', 'import_function' );
function import_function() {
$product_id = ( ! empty( $_POST['product_id'] ) ) ? $_POST['product_id'] : 1;
$url = 'https://example.com/products/';
$args = array(
'headers' => array(
'Content-Type' => 'application/json',
'X-Api-Key' => 'apikey12345'
)
);
// this call the function and return the body
$results = wp_remote_retrieve_body(wp_remote_get($url . $product_id, $args));
// convert to array
$results = json_decode( $results );
// Stop the code execution on this conditions
if( ! is_array( $results ) || empty( $results ) ){
return false;
}
// Do your product creation here...
$product_id++; // increase $product_id
wp_remote_post( admin_url('admin-ajax.php?action=import_function'), [
'blocking' => false, // needed for the script to continue running on the background
'sslverify' => false, // needed if working on localhost.
'body' => [
'product_id' => $product_id
]
] );
}
OK, I managed to get it to work. I assume that it's dumb way to do this, but since it works it's fine for me. The only thing that is problematic now is the fact that the code for image import that I used previously (when code ran in browser) now makes the plugin stuck. Without it it works great and fast. Here is my current code:
<?php
/**
* Plugin Name: Product Importer
* Description: Imports products from an external API
* Version: 3.0
* Author: me
* Author URI: http://www.example.com
*/
register_activation_hook( __FILE__, 'schedule_import' ); //plugin starts when activated, fine for me
function schedule_import() {
wp_schedule_single_event( time(), 'import_products' );
}
add_action( 'import_products', 'import_function' );
function import_function() {
$batch_size = 50; //when split into batches it worked faster than one products after another, so ok
$batch_delay = 60; //give it some time to finish batch, to avoid problems
$last_imported_product_id = get_option( 'last_imported_product_id', 1 ); //need it for incrementation and rescheduling
$api_key = 'apikey123456789';
$headers = array(
'X-Api-Key: ' . $api_key,
);
$url = 'https://example.com/products/';
for ( $i = 0; $i < $batch_size; $i++ ) {
$product_id = $last_imported_product_id + $i;
$product_url = $url . $product_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $product_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$product_data = json_decode($response, true);
$post = array(
'post_title' => $product_data['name'],
'post_content' => $product_data['description'],
'post_status' => 'publish',
'post_type' => 'product',
'meta_input' => array(
'_virtual' => 'yes',
'_regular_price' => $product_data['price'],
),
);
$post_id = wp_insert_post($post);
update_post_meta($post_id, '_sku', $product_data['Id']);
wp_set_object_terms($post_id, 'external', 'product_type');
$external_url = 'https://example.external.url';
update_post_meta( $post_id, '_product_url', $external_url );
update_option( 'last_imported_product_id', $product_id + 1 ); //incrementation of product_id for rescheduling
wp_schedule_single_event( time() + $batch_delay, 'import_products' ); //rescheduling
}
}
This above works well. However when I add my old code for image imports it imports nothing or 1 product (without image lol) and becomes stuck. After a minute it imports the same product over and over again. Old code for image import:
// Get the product images
$images = $product_data['images']['screenshots'];
$image_ids = [];
foreach ($images as $image) {
// Download the image
$image_url = $image['url'];
$response = wp_remote_get($image_url);
if (is_array($response)) {
$image_data = $response['body'];
$filename = basename($image_url);
$file_array = array(
'name' => $filename,
'tmp_name' => download_url($image_url),
);
// Insert the image into the media library
$attach_id = media_handle_sideload($file_array, $post_id);
if (!is_wp_error($attach_id)) {
array_push($image_ids, $attach_id);
}
}
// Set the product image gallery
update_post_meta($post_id, '_product_image_gallery', implode(',', $image_ids));
// Set the product featured image
update_post_meta($post_id, '_thumbnail_id', $image_ids[0]);
And no, I don't put it after rescheduling, but after $post array.
Honestly no idea why it would crash, tried smaller batches, longer wait between batches etc. I assume the code for images import is just very poorly written. Any solutions for this problem are going to be very appreciated ! :)
PS: I am totally fine with importing the first image available (there is around 6) and setting it up as thumbnail for product. I can give up on the gallery since It's going to slow down the process anyway.
EDIT: here is the fragment of json file received from api. (for better context of importing images):
"images":{
"screenshots":[
{
"url":"https://example.jpg",
"thumbnail":"https://example.jpg"
},
{
"url":"https://example.jpg",
"thumbnail":"https://example.jpg"
},
{
"url":"https://example.jpg",
"thumbnail":"https://example.jpg"
etc....
I am trying to create a rebrandly short link using a WordPress shortcode. Here's what I have so far:
add_shortcode( 'shortlink', 'rebrandly_shortcode');
function rebrandly_shortcode( $content = null ) {
$domain_data["fullName"] = "rebrand.ly";
$post_data["destination"] = $content;
$post_data["domain"] = $domain_data;
$ch = curl_init("https://api.rebrandly.com/v1/links");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"apikey: 67c55f8b4e5d4f079cfc866b2b80b4f5",
"Content-Type: application/json"
));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);
return "Short URL is: " . $response["shortUrl"];
}
Following the directions for PHP here - https://developers.rebrandly.com/docs
The shortcode I'm testing is [shortlink]https://example.com[/shortlink] but its not working.
When I change the part:
$post_data["destination"] = $content;
to
$post_data["destination"] = "http://example.com";
it works.
I must be putting in the shortcode content wrong. Any ideas?
You are missing an argument in your shortcode function. The the parameter list for all shortcode functions is ($attributes, $content=null). This means that first parameter passed in by Wordpress is going to be the attributes (whether you have any or not), and the content between the shortcode tags is second.
Your code is trying to use the first parameter as $content, but as WP is actually passing in attributes first, this is empty in your case.
You just need to change your function to match the defined parameter list to include both arguments (even if you don't have any attributes), i.e.:
// $attributes argument first, $content second
function rebrandly_shortcode( $attributes, $content = null ) {
// do your stuff here
}
FYI
Shortcode attributes are information you can add to the shortcode to be used in the function, for example a class, some text to include, or anything else.
If we take your code as an example, you could pass in different shortlink domains on different pages as follows (obviously this isn't a practical example, but it shows how it works!)
[shortlink domain="rebrand.ly"]
Then the function can extract the attributes to be used as follows:
function rebrandly_shortcode( $attributes, $content = null ) {
// extract the apikey attribute into a variable called $domain
extract( shortcode_atts( array(
'domain' => '' // you could also give it a default value here instead of ''
), $attributes ) );
// use your domain parameter
$domain_data["fullName"] = $domain;
// do the rest of your stuff
}
I am trying to fetch data from this API:
https://rapidapi.com/apilayernet/api/rest-countries-v1?
endpoint=53aa5a08e4b0a705fcc323a6
I managed to use wp_remote_get() to make the request but I keep getting no result showing up apart from an error:
The site is experiencing technical difficulties.
I just point out thatI have used Composer to set up the Composer.json file in my XAMPP proper folder in which I have included the request:
{
"require-dev": {
"mashape/unirest-php": "3.*"
}
}
In my code I am including the parameter for the API key as below but for some reason is not working:
$request = wp_remote_get( 'https://restcountries-v1.p.rapidapi.com/all',
array(
"X-RapidAPI-Host" => "restcountries-v1.p.rapidapi.com",
"X-RapidAPI-Key" => "7fc872eb0bmsh1baf0c288235a1ep114aecjsn18f888f020c0"
) );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
echo $data;
The wp_remote_get accepts an array of options as the second argument, but you passed the headers directly.
They should be inside a nested headers array inside the options.
Method Documentation: https://codex.wordpress.org/Function_Reference/wp_remote_get
$request = wp_remote_get('https://restcountries-v1.p.rapidapi.com/all', [
'headers' => [
'X-RapidAPI-Host' => 'restcountries-v1.p.rapidapi.com',
'X-RapidAPI-Key' => '<apikey>',
],
]);
if (is_wp_error($request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
echo $data;
This is the method I use on all of my gets from Wordpress
$url = 'https://restcountries-v1.p.rapidapi.com/all'; //define url
$response = wp_remote_get($url, array(
'headers'=> array('X-RapidAPI-Host' => 'restcountries-v1.p.rapidapi.com', //set header
'X-RapidAPI-Key' => '<apikey>'//set api key
),
'method' => 'GET',//set method
));
$decode = json_decode($response);// decode response
echo "<pre>"; print_r($decode); die('dead');// display response on page wiothout any other information.
Wordpress version 4.7.5
I am signing up new users from Instagram, I am successfully able signup the new user. after signup I am trying to logged in the user.
I can use hook, but would like better solution than the dirty one, I
have posted as that will be totally unuseful .
if( $user_created ) {
$new_user = get_user_by( 'id', $user_created );
//$loggedin = programmatic_login( $new_user->user_login );
//ob_start();
if ( !is_user_logged_in() ) {
wp_clear_auth_cookie();
wp_set_current_user( $user_created, $new_user->user_login );
wp_set_auth_cookie( $user_created, true );
do_action( 'wp_login', $new_user->user_login );
// wp_safe_redirect(site_url() . '/profile/');
// exit;
// $redirect_to=user_admin_url();
// wp_safe_redirect($redirect_to);
// exit();
}
//ob_end_clean();
} ?>
<script>jQuery(document).ready(function(){ window.location.href = "<?php echo site_url() . '/profile/'; ?>";});</script> <?php
also tried with a custom programmatic_login function from another post.
if I am trying to var_dump wp_get_current_user() and $_COOKIE below this, I am getting user object for wp_get_current_user() and array(1) { ["wordpress_test_cookie"]=> string(15) "WP Cookie check" } for $_COOKIE .
Important Edit
The code is inside a function, which is hooked to a hook, that is called in side a page that is after header is getting displayed, so we could not use init here. any other way of doing it and also because of this wp_safe_redirect() or header('Location: ') also not working .
Important Update with what I have just tried
A dirty work around
when I created the user from Instagram login, After successful creation I redirected the user to a page with get parameter something like ?user_id=$inserted_id and on wp hook, I tried to get the GET['user_id'] and logged it and it worked, trying to find a proper solution.
if ( $wpdb->insert_id ){ //that is registration with instagram
?>
<script>jQuery(document).ready(function(){ window.location.href = "<?php echo get_bloginfo('url') . '/profile/?id=' . $wpdb->insert_id; ?>";});</script>
<?php
}
and then
add_action( 'wp', 'login_current_user' );
function login_current_user(){
if ( is_page() && get_the_id() == 863 ){
if ( isset( $_GET['id'] ) ){
if ( !is_user_logged_in() ) {
$user_id = $_GET['id'];
$user = get_user_by( 'id', $user_id );
wp_clear_auth_cookie();
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id, true );
do_action( 'wp_login', $user->user_login );
if ( is_user_logged_in() ){
$redirect_to=site_url() . '/profile';
wp_safe_redirect($redirect_to);
exit();
}
}
}
}
}
Proble with dirty trick. If the id we are passing as get parameter
exists in wp_users table then with no verification that will be logged
in .
Update
I created a user_meta before redirecting to profile page and after verification login the user and removed the usermeta, just like an OTP . Trying to make it better if possible.
Below the code:-
if ( $wpdb->insert_id ){ //that is registration with instagram
$temporary_token = sha1(rand());
update_user_meta( $wpdb->insert_id, 'temporary_token', $temporary_token);
?>
<script>jQuery(document).ready(function(){ window.location.href = "<?php echo get_bloginfo('url') . '/profile/?id=' . $wpdb->insert_id . '&token=' . $temporary_token; ?>";});</script>
<?php
}
and then
add_action( 'wp', 'login_current_user' );
function login_current_user(){
if ( is_page() && get_the_id() == 863 ){
if ( isset( $_GET['id'] ) ){
if ( !is_user_logged_in() ) {
$user_id = $_GET['id'];
$user = get_user_by( 'id', $user_id );
if ( $_GET['token'] == get_user_meta( $user_id, 'temporary_token', true ) ){
delete_user_meta( $user_id, 'temporary_token', $_GET['token'] );
wp_clear_auth_cookie();
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id, true );
do_action( 'wp_login', $user->user_login );
if ( is_user_logged_in() ){
$redirect_to=site_url() . '/profile';
wp_safe_redirect($redirect_to);
exit();
}
}
}
}
}
}
If headers have been sent before wp_clear_auth_cookie() or wp_set_auth_cookie() are called then neither will work as both rely on PHP's setcookie function. The after_setup_theme action will occur before headers have been sent so hooking that and setting the cookies there should fix the issue.
function myPlugin_createUser(){
// Probably need to put code that creates user here too otherwise $user_created will never return true
if( $user_created ) {
$new_user = get_user_by( 'id', $user_created );
if ( !is_user_logged_in() ) {
wp_clear_auth_cookie();
wp_set_current_user( $user_created, $new_user->user_login );
wp_set_auth_cookie( $user_created, true );
do_action( 'wp_login', $new_user->user_login );
}
}
}
add_action( 'after_setup_theme', 'myPlugin_createUser' );
Update:
If you're outputting view elements before triggering your createUser function it won't work so we need to make sure they run completely independent of each other. Below I've put together a simple example of how to achieve this - to the view we output a link which passes a GET parameter, this parameter is picked up by the plugin and runs the action before anything is rendered allowing us to set the cookie.
my-plugin.php
// Note: you'll need to include a completed version of myPlugin_createUser() function as above for these examples to work
add_shortcode( 'my-plugin', function() {
// I've used a GET request for simplicity- a form + POST request may be more practical for your purposes and will prevent caching issues.
echo "<a href='?my_plugin_login_user=1'>Login</a>";
});
// Check for our GET parameter
if( isset( $_GET['my_plugin_login_user'] ) ) {
// Nothing should be rendered yet as plugin template hasn't even started loading yet so cookies should set fine
add_action( 'plugins_loaded', 'myPlugin_createUser' );
}
page-my-template.php
<div> ...
<?php
do_shortcode( 'my-plugin' );
?>
</div>
Update 2:
If using Instagrams Authentication API the explicit flow outlined https://www.instagram.com/developer/authentication/ (most of the examples used below are taken from there) is probably the best approach. Below I'll give a brief rundown of how you could implement it. Much of it is taken from there with notes added.
Send the user off to https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
You could include the WordPress user ID as a parameter on the callback URL or if the user hasn't yet been created and you need to maintain state then you'll need to generate a temporary token that you can use later that's been associated with said data or store that data client side if it's not sensitive which is probably easier and better as it doesn't require a user to be logged in to function.
The user will then login
Not much to say about this step - if an error occurs they'll be redirected to http://your-redirect-uri?error=access_denied&error_reason=user_denied&error_description=The+user+denied+your+request
If login is successful the user will be redirected to http://your-redirect-uri?code=CODE
The CODE passed back on the redirect URL we can redeem for an access token.
So from here there's a multitude of ways we can handle it but essentially what we need is an endpoint for the redirect that we have sufficient control over to send HTTP headers before any of the HTTP response body is sent.
Methods of approaching this (not an exhaustive list):
Conditionally hooking on pages Instagram auths are allowed (as in your examples). This has the advantage of not requiring an additional redirect.
Custom page template
External script that manually bootstraps WordPress does what we need, then redirects back in
So now once we've got an endpoint setup we need to redeem the CODEfor an access token. Adapted this snippet from https://gist.github.com/arturmamedov/7f5a90b85a20e06e344ebb88dc898d25
$uri = 'https://api.instagram.com/oauth/access_token';
$data = [
'client_id' => '213esdaedasdasd12...YOUR_CLIENT_ID',
'client_secret' => 'a8b4aaf06c0da310...YOUR_CLIENT_SECRET',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://www.YOUR_REDIRECT_URL.it', // The exact redirect URL as used previously
'code' => $_GET['code']
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri); // uri
curl_setopt($ch, CURLOPT_POST, true); // POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // POST DATA
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // RETURN RESULT true
curl_setopt($ch, CURLOPT_HEADER, 0); // RETURN HEADER false
curl_setopt($ch, CURLOPT_NOBODY, 0); // NO RETURN BODY false / we need the body to return
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // VERIFY SSL HOST false
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // VERIFY SSL PEER false
$result = json_decode(curl_exec($ch));
$result will be an object representation of the JSON response:
{
"access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
"user": {
"id": "1574083",
"username": "snoopdogg",
"full_name": "Snoop Dogg",
"profile_picture": "..."
}
}
From here we just create our user/authenticate with WordPress and redirect to the desired page/render the template (no need to redirect if handled via conditional hooks) and restore the page state if needed.
I'm building a Twitter application which depends on retrieving Twitter search results. It works fine but I still need to update the page to get the new tweets.
How to let the page refreshes itself dynamically just like Twitter Widgets, to show the new tweets ?
Here is my code, please show me how, because I tired many scripts and it doesn't work with me.
Twitter Class
<?php
class Twitter
{
public function __construct(){ }
public function searchResults( $search = null )
{
$url = "http://search.twitter.com/search.atom?q=" . urlencode( $search ) . "&lang=en&rpp=50";
$curl = curl_init();
curl_setopt( $curl, CURLOPT_URL, $url );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
$result = curl_exec( $curl );
curl_close( $curl );
$return = new SimpleXMLElement( $result );
return $return;
}
}
?>
Test Class
<?php
require_once("twitter.class.php");
$Twitter = new Twitter;
$results = $Twitter->searchResults("usa");
foreach( $results->entry as $result )
{
echo "<h3><a href=\"". $result->author->uri ."\">". $result->author->name ."<a/></h3><img src=\"". $result->link[1]->attributes()->href ."\" style=\"float: left;\"><p>". $result->content."</p><div style=\"clear:both;\"> </div>";
}
?>
.
.
Waiting for your response :)
You could poll for changes through javascript / ajax, by setting up a timer that calls a function in Test Class which returns a list of tweets. Example (using jquery because I am no javascript expert):
$(function() {
function fetchTweets() {
$.ajax({
url: "testclass.php",
success: function(data) {
// Replace contents of one element with data
}
}
setInterval(fetchTweets(), 60000);
}