Monday, December 16, 2013

Useful snippets for php developers


Extract keywords from a webpage

The title said it all: A great code snippet to easily extract meta keywords from any webpage.

<?php 
$meta = get_meta_tags('http://www.emoticode.net/');
$keywords = $meta['keywords'];
// Split keywords
$keywords = explode(',', $keywords );
// Trim them
$keywords = array_map( 'trim', $keywords );
// Remove empty values
$keywords = array_filter( $keywords );

print_r( $keywords );
?>

Find All Links on a Page

Using the DOM, you can easily grab all links from any webpage. Here’s a working example:

<?php 
$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
       $href = $hrefs->item($i);
       $url = $href->getAttribute('href');
       echo $url.'<br />';
}
?>

Create Data URI’s

Data URI’s can be useful for embedding images into HTML/CSS/JS to save on HTTP requests. The following function will create a Data URI based on $file for easier embedding.

function data_uri($file, $mime) {
  $contents=file_get_contents($file);
  $base64=base64_encode($contents);
  echo "data:$mime;base64,$base64";
}

Download & save a remote image on your server

Downloading an image on a remote server and saving it on your own server is useful when building websites, and it’s also very easy to do. The two lines of code below will do it for you.

$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //Where to save the image

Detect browser language

If your website is multilingual, it can be useful to detect the browser language to use this language as the default. The code below will return the language used by the client’s browser.

function get_client_language($availableLanguages, $default='en'){
 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

  foreach ($langs as $value){
   $choice=substr($value,0,2);
   if(in_array($choice, $availableLanguages)){
    return $choice;
   }
  }
 } 
 return $default;
}

Display number of Facebook fans in full text

If you have a Facebook page for your website or blog, you might want to display how many fans you have. This snippet will help you to get your Facebook fan count, in full text. Don’t forget to add your page ID on line 2.

<?php
 $page_id = "YOUR PAGE-ID";
 $xml = @simplexml_load_file(
"http://api.facebook.com/restserver.php?method=facebook.fql.query&
query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") 
or die ("a lot");
 $fans = $xml->page->fan_count;
 echo $fans;
?>

Source From: http://www.catswhocode.com

No comments:

Post a Comment