Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Friday, March 11, 2011

Grabbing only Pictures out of an XML feed

Pulling Images from feeds with Google AJAX Feed API and Regular Expressions



Recently, I have been building a super aggregator and search engine website using various google APIs. The search engine is using the Google search API and most of the rss and xml aggregation is handled using the Google AJAX Feed API. But, in order to retrieve only the images out of the xml feed, I had to make modifications to the standard Google Feed API.

The xml feed had some images and some other links and text, but I just wanted to grab the linkable pictures so I had to write an extra function and use regular expressions to get rid of the content i did not want. I assume that this piece of code could be useful to other who want to just pull images out of an xml feed that contains more than just pictures.

Here is the JavaScript excerpt:

[sourcecode language="JavaScript"]
<script type="text/javascript">
google.load("feeds", "1");

function replaceit(matches){
var pattern = new RegExp("<img([^>]+)(\s*[^\/])>", "g");
return matches.match(pattern);
}

function initialize() {
var feed = new google.feeds.Feed("http://feeds.feedburner.com/TechCrunch?format=xml");
feed.setNumEntries(20);

feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
var wow = replaceit(entry.content);
div.innerHTML = wow;
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
</script>
[/sourcecode]


Here is how the code works:

You define the feed on line 10, and on line 11 you set the number of entries you want to pull from the XML feed with set setNumEntries() function. If the feed loads successfully line 16 loops through the 20 items and pulls the content out of the feed. The content contains some text and links that I need to get rid of so line 19 runs the content through a function I set up on line 4.

The function uses regular expressions to retrieve the img tags and only return the images. Line 21 injects the results into the div specified on line 15 and it uses appendChild to get it done. Hopefully, this is useful to someone!

Friday, March 4, 2011

Feeds in your Blog with Google Ajax Feed API

Put RSS Feeds in your WordPress blog without extra plugins or jQuery



I started using the Google Ajax Feed API and i really like it, so I decided to write a WordPress plugin that will use the API to place rss or xml feeds on your wordpress blog. There are plugins out there already that allow you to put feeds on your blog, and one of them actually uses the Google API, it's called jQuery Google Feed Plugin but as the name suggests it also uses jQuery. jQuery is a wonderful JavaScript library but sometimes I use prototype and I don't want to load both libraries. Actually, I don't want to load any extra library, and after looking at the simplicity of implementing this, I decided that writing a wordpress plugin for this is a waste of time. Anyone can insert feeds inside their wordpress blog with just a couple quick steps:

First, get your own free Google API key and insert this javascript in the header.php file right between the <head> and </head> tag:

[sourcecode language="javascript"]
<script type="text/javascript" src="http://www.google.com/jsapi?key=YOUR-GOOGLE-API-KEY-HERE"></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() {
var feedControl = new google.feeds.FeedControl();
feedControl.addFeed("http://www.digg.com/rss/index.xml", "Digg");
feedControl.addFeed("http://feeds.feedburner.com/Techcrunch", "TechCrunch");
feedControl.setNumEntries(10);
feedControl.draw(document.getElementById("feedControl"));
}
google.setOnLoadCallback(initialize);
</script>

[/sourcecode]

Now, go anywhere in your blog where you want the feeds to appear and create the div where you want the results to be displayed:

<div id="feedControl"></div>

This feed technique will allow you to insert as many feeds as you want into your blog and configure the titles, number of entries, and the style via css.

feedControl.addFeed("http://www.digg.com/rss/index.xml", "Digg"); - Here the feed url is http://www.digg.com/rss/index.xml and feed title is Digg, you can change these or add another feed using the same format.

feedControl.setNumEntries(10); - The number 10 here represents how many entries you want to display, change it if you want to show less or more than 10 entries per feed.

If you don't like this technique and still want to insert feeds into your WordPress blog, you can try these plugins:

Wednesday, March 2, 2011

Link Equity or Link Popularity

Your web page's link equity is a very significant factor that affects your placement in search engine result. Link popularity is another name for link equity and it refers to relevance of a web page by looking at its links. It's a mathematical method to calculate your online existence. Simply, a web page with more quality incoming links is more important then another web page with fewer incoming links. Incoming links refers to links that are coming from other websites to your web page. Quality of the incoming links is very important as not all incoming links are counted equal. In fact, the quality of incoming links counts more than the quantity.

Over time, your website will acquire many incoming links and search engines will give you better results. Thus, if you make changes to your website through some redesign or redevelopment, remember not to lose your link popularity. If you change your URL structure, you should utilize a 301-permanent-redirect to transfer the equity. Otherwise, you will lose search engine ranking equity, bookmark equity, and direct citation equity.

The 301 status code notifies the search engine that the resource has been "moved permanently" to a new location. It also tells search engines that the link equity from the previous URL should be credited to the new one, but in practice, it may take some time for this to occur. There are many ways to code this redirect, below there are php and .htaccess examples:

How to do a 301 Redirect with PHP:
[sourcecode language="php"]
<?php Header( "HTTP/1.1 301 Moved Permanently" ); Header( "Location: http://www.new-url.com" ); ?>
[/sourcecode]

How to do a 301 Redirect with .htaccess:

To Move a single page:
Redirect 301 /oldpage.html http://www.example.com/newpage.html

To change domain names:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^.*oldwebsite.com$ [NC]
RewriteRule ^(.*)$ http://www.preferredwebsite.net/$1 [R=301,L]

Wednesday, February 16, 2011

Retrieving Data from MySQL DataBase with PHP

A ton of websites use PHP and MySQL for web development and most of the time they are built around some Content Management System that handles database interaction. However, if you are interested in learning how to simply interact with the database using php, then I will provide a nice example. The PHP mysql_fetch_array() function returns an array of the requested data from the table. Then, a while loop assigns a row’s data to an array called $row and the value associated with the column name on each row is written out. The following php code is modified from a Mike McGrath’s PHP for WINDOWS and LINUX book:

[sourcecode language="php"]
<html><head><title>Get Data</title></head>
<body>

<?php
#connect to MySQL
$conn=@mysql_connect("localhost","user","password") or die("Err:conn");

#select the specified database
$rs=@mysql_select_db("database_name", $conn) or die("Err:Db");

#create the query
$sql="select id,cat_name from table";

#execute the query
$rs=mysql_query($sql,$conn);

#write the data
while( $row = mysql_fetch_array($rs) )
{
echo("ID: ".$row["id"]);
echo(" Print Data: ".$row["cat_name"]."<br>");
}
?>
</body>
</html>
[/sourcecode]

I tested the script and it works great. Make sure that the table exists in your database and it has what you are trying to pull. I had something under id and something under cat_name in my table so it showed me the appropriate values. If you have questions, send me an email or comment.

Tuesday, February 8, 2011

Six Ways to Redirect Visitors to a New Url

PHP, JavaScript, META and Htaccess Redirection



Do you need to redirect your users to another page? There are a six different ways you can get it done, two methods using PHP, two methods using JavaScript, and one way using META Refresh or via htaccess file. There are different reasons for using different methods. Here is the code with some explanations:

1. Direct PHP Redirect: This is a direct redirection using server side PHP code without any delay. No client side code is processed (no infomation is sent to the browser), the user is immediately taken to the page specified in the PHP file.

[sourcecode language="php"]
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
[/sourcecode]

2. PHP Redirection with Delay: This is a PHP redirect with a specified delay in seconds. During this delay, PHP code can be processed and passed to the browser. Using the code below, the user will see the message “You will be re-directed in 5 seconds…” for 5 seconds before the browser redirects user to the page specified.

[sourcecode language="php"]
header( "refresh: 5; url=http://www.example.com/" );
echo "<h1>You will be re-directed in 5 seconds…</h1>";
[/sourcecode]

3. JavaScript Direct Redirection: If you don’t know PHP you can use JavaScript to redirect. JavaScript is done on client side so it even though this is a direct redirection, it can still send information to the browser. This means that you can process some javascript and then redirect the user, or redirect the user based on some process; in the first example of PHP direct redirection you cannot process anything on the client side.

[sourcecode language="JavaScript"]
window.location = "http://www.google.com/"
[/sourcecode]

4. JavaScript Redirection with Delay: This is almost the same as the direct javascript redirection shown above, however, here you can specify a delay time similar to the delay time specified in the second PHP example. 5000 means 5 seconds.

[sourcecode language="JavaScript"]
setTimeout("location.href=’http://www.google.com/’", 5000);
[/sourcecode]

5. Meta Refresh Redirection: This redirection method uses a HTML meta element to tell the web browser to automatically redirect the user to another web page after some time. According to W3C, it is bad practive to use META to redirect becasue it does not give any info about either the original or new resource to the browser or search engine. The “back” button will also not work in some browsers. But, it’s still another way to get the job done.

[sourcecode language="html"]
<meta http-equiv="refresh" content="5;url=http://www.google.com/" />
[/sourcecode]

6. Htaccess Direct Redirectionn: My favorite way of redirecting is by using the .htaccess file. It has no delay because it is done server side and visitors get sent directly to the new page before the original page is server to the browser. Here are some ways of redirecting using the htaccess file (301 means Moved Permanently):

To Move a single page:

Redirect 301 /old-web-page.html http://www.example.com/new-web-page.html

To Move an entire site:

Redirect 301 / http://www.example.com/

Redirect www to non www version of site:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^example\.com
RewriteRule (.*) http://example.com/$1 [R=301,L]

Redirect non-www to www:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursite.com [NC]
RewriteRule ^(.*)$ http://www.yoursite.com/$1 [L,R=301]

Tuesday, February 1, 2011

Regular Expressions - Resources, Samples, and Regex Information

Regular Expression Books

Regular Expressions are a really powerful, useful, and precise means for matching strings of text via a given pattern. They are also referred to as regex or regexp. If you have been doing any kind of development, front-end or back-end, you have probably used or seen them in action. In the front-end world, form validation comes to mind right away, but there are many uses, and it's a good idea to have some fundamental knowledge about regular expressions.

In this article I will try to provide some of the best links to resources available on the internet for regular expression tutorials, tools, patterns, and regex information. I hope it will be helpful to anyone that wants to learn more about regex or someone that is just looking for a pattern for their code. If you prefer to read a real book instead of looking at online text, I would definitely recommend Mastering Regular Expressions by Jeffrey Friedl.

As a start, I think a good place to begin learning about regular expressions is glancing at the wikipedia regex entry. Wikipedia gives you a good overview of basic concepts, history, and some good regular expression patterns and metacharacters to remember. After you have this overview, the best place to learn about regular expressions online is definitely the regular-expressions.info website. Most people that work with regular expressions daily always recommend this site as a super informative resource. Also, while you are getting introduced to regex, download a regular expression cheat sheet.


Learning Regular Expressions



If you are looking for more explanations on why and how things work in the world of regex, I would recommend these links:

How to Regex

Mastering Regular Expressions

PHP Regular Expressions

Regular Expressions for SEO


Learning Regular Expression Patterns and Samples



Most people don't really want to learn regular expressions but they are searching for a pattern for their code and need a good resource to find good regex samples and examples. The obvious problem with that is that you are just taking a guess that the pattern is good without really knowing what you are doing... but these resources are really good and provide many patterns with explanations and helpful descriptions. Also, looking at these patterns can help you learn more about regular expressions:

Regex Patterns

JavaScript Regex

Regular Expressions for Web Developers

Intro to PHP Regex

Programming Regular Expressions

Password Strength Regex

URL validation via Regex


Online Regex Testers



While you are reading about regular expressions and browsing through patterns, you probably want to try some of these yourself. Well, there are many options, you could write a quick regex tester yourself in PHP, JavaScript, or whatever language you are most comfortable with, but why not just try one of the many online regular expression tools available on the internet. Here is a list of great regex online editors (most of these have some good information and sample patterns that you can test out for yourself):

gSkiner RegExp

Rubular

RegTest Tester

Regex Pal

Regex Editor

Regex Tool


Finally, if you are looking for even more links and information on regular expressions, I think these two articles do a good job on giving you extra resources:

Essential Guide to Regular Expressions

You don't know anything about Regular Expressions

Monday, January 31, 2011

Improve Website Performance with better CSS code

This is something you should think about, everybody wants a fast page load and good website performance. Most of the time, this problem is a discussed as a client-side JavaScript issue, but sometimes, we can optimize browser rendering with better CSS code.

I'm not referring to things like minifying CSS, compression, or techniques like CSS Sprites, which definitely improve performance, but this is a good place to start thinking about CSS optimization. I want to discuss straight CSS coding and explain how you can write better CSS code by efficiently using CSS selectors.


1. Order of most efficient to least efficient: ID, class, tag, and universal. Thus, you should generally avoid the universal key selector (body > * {…}) and overall, make your rules as specific as possible.

2. Descendant selectors are really inefficient (html ul li a {…}) especially the tag or universal selectors. This is because browsers read CSS selectors from right to left. So, when the browsers evaluate even a simple tag descendant selector (#main li {…}) they do not look for the ID first and the tag children second. Instead, the browser finds all the li tags in the DOM, and then traverses up the DOM tree to find the matching #main ID selector.

3. Avoid using overly qualified selectors. I see this all the time (ul#nav {…}) and its just wasteful because ID selectors are unique by definition (ul#nav {…} = #nav {…}) so the tag name UL is not needed and extra information for the browser to evaluate. If you are thinking about readability, then just use a comment(/*ul*/ #nav {…}).

4. Rely on inheritance, learn which CSS properties inherit, and let them inherit, write less code, give the browser less work.

5. Avoid using redundant ancestors in descendant selectors. The descendant selector shown above (html ul li a {…}) has a redundant html selector, since all elements are descendants of the html tag.

6. Avoid using :hover on non-anchor elements as you might his performance issues in IE7 and IE8, and if you are coding for all browsers, you already know it does not work in IE6.

7. You should probably avoid CSS3 selectors (:nth-child) completely because they are really inefficient. Plus, they do not work in older browsers. Of course, if you don't care about certain browsers, and the alternative to CSS3 is some JavaScript code, it might be better to use CSS3.

These are some things you should be thinking about when doing xhtml/css code. These are not rules, but just advice on how to code CSS for better performance. Following these guidelines completely is actually pretty impractical as you would have a fast page with all unique ID's which is non-semantic and hard to maintain. But, it's still good information to know, and sometimes, it can help you write better CSS code.



Source and more Links: