Tuesday 20 August 2013

PHP Translator, replacement for google translator api?.


I struggled to get the language translator for my php project and found Google API is not WORKING FOR ME, I dont know it works for others. While surfed i got google closed its Free Translator API, and microsoft is providing its API with limited character free subscription.

The code providing by them comes in SOAP, HTTP and Javascript and yes it supported my PHP. Even they are providing exact PHP class files that helped me a lot. You can register your Keys with them, use this link for to Sign up for the Microsoft Translator API "https://datamarket.azure.com/dataset/1899a118-d202-492c-aa16-ba21c33c06cb". They have listed all the subscription plans ranges from free to $6000/ month.

I think this link will also helpful http://www.microsofttranslator.com/dev/. After creating your Keys register with Datamarket and your translator will work good. I have used HTTP >> Translate Method "http://msdn.microsoft.com/en-us/library/ff512421.aspx" and there you can see the PHP class files, and it is very handy......


Happy coding

Monday 19 August 2013

How to get the meta title, description and keywords using PHP



function getUrlData($url)
{
    $result = false;
   
    $contents = getUrlContents($url);

    if (isset($contents) && is_string($contents))
    {
        $title = null;
        $metaTags = null;
       
        preg_match('/<***title***>([^***>]*)<***\/title***>/si', $contents, $match );

        if (isset($match) && is_array($match) && count($match) > 0)
        {
            $title = strip_tags($match[1]);
        }
       
        preg_match_all('/<***[\s]*meta[\s]*name="?' . '([^***>"]*)"?[\s]*' . 'content="?([^***>"]*)"?[\s]*[\/]?[\s]****>/si', $contents, $match);
       
        if (isset($match) && is_array($match) && count($match) == 3)
        {
            $originals = $match[0];
            $names = $match[1];
            $values = $match[2];
           
            if (count($originals) == count($names) && count($names) == count($values))
            {
                $metaTags = array();
               
                for ($i=0, $limiti=count($names); $i <*** $limiti; $i++)
                {
                    $metaTags[$names[$i]] = array (
                        'html' => htmlentities($originals[$i]),
                        'value' => $values[$i]
                    );
                }
            }
        }
       
        $result = array (
            'title' => $title,
            'metaTags' => $metaTags
        );
    }
   
    return $result;
}

function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
    $result = false;
   
    $contents = @file_get_contents($url);
   
    // Check if we need to go somewhere else
   
    if (isset($contents) && is_string($contents))
    {
        preg_match_all('/<***[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^***>"]*)"?' . '[\s]*[\/]?[\s]****>/si', $contents, $match);
       
        if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
        {
            if (!isset($maximumRedirections) || $currentRedirection <*** $maximumRedirections)
            {
                return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
            }
           
            $result = false;
        }
        else
        {
            $result = $contents;
        }
    }
   
    return $contents;
}
?>


<***?php
$result = getUrlData('http://elwatannews.com/');

echo '<***pre***>'; print_r($result); echo '<***/pre***>';


Note: Remove ***s

Friday 16 August 2013

How to Resize or Scale your image using CSS

There are many best ways to scale the images for your site. We can use the php resize codes or Jquery resize scripts and others, and one of the best way is to scale the images through CSS. For a demo please check the below code



<*****style type="text/css">
.center-cropped  {
    width: 310px;
    height: 168px;
    background-position: 50% 11%;
    background-size: cover;
 }

<*****div class="center-cropped" style="background-image: url('http://elbadil.com/sites/default/files/styles/428xauto_node_image_2/public/13/08/32/0_73.jpg?itok%3Dk9uRSMGi');">
<******/div>


Note: remove ******


In the above code background-size acts as the center point, I just need a whole cover section, but we can use contain or auto or anything as per your needs.

Check the background-position too. I made as 50: 11 Percentage ratio. You can set the height and width and by this there wont be any stretch in the image. But the whole concept will make the load time bit high when compared to resizing :)




Code to make other site image to get stored in your wordpress database as well as making other site images to your wordpress post featured image


$upload_dir = wp_upload_dir();
$image_data = file_get_contents("Image URL for other site");
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir['path']))
$file = $upload_dir['path'] . '/' . $filename;
else
$file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);

$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id , $attach_id );


wp_update_attachment_metadata will make the image to get stored in your database

set_post_thumbnail will make the image to get featured for the post

$post_id - will be ID of your post, for example if you just want to make your post id 5 to get featured image then just replace the variable  $post_id with 5





substr in php is not removing characters?


I had a similar problem before and rectified using mb_substr, for demo please check the below code

$then_truncate_the_value=mb_substr($remove_html_first , 0, 123);

How to scrap the titles of a Wordpress site using CURL php?


$curl1 = curl_init();
curl_setopt($curl1, CURLOPT_URL, 'Your URL');
curl_setopt($curl1, CURLOPT_HEADER, false); 
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl1, CURLOPT_FOLLOWLOCATION,true);
curl_setopt($curl1, CURLOPT_ENCODING,"");
curl_setopt($curl1, CURLOPT_USERAGENT, "spider");
curl_setopt($curl1, CURLOPT_AUTOREFERER,true);
$result1 = curl_exec($curl1); curl_close($curl1); 


## get the title
preg_match_all('your h1 tag with calss', $result1, $matches1, PREG_OFFSET_CAPTURE);
preg_match('/your anchor tag/', $matches1[0][0][0], $set1);
$my_title=$set1[2];



1) Initialize the CURL
2) Enter the URL
3) Check whether the wordpress site comes with the h1 tag and with the same class i declared here, else use the correct one
4) I dont want the link tag so i removed the <--a---> tag, and finally we will have the result

How to get images for a URL through php?

We can use many concepts for this eithe we can use DOM or CURL or anything. Lets see a simple example on how to use DOM concept





$doc = new DOMDocument();
$doc->loadHTML('Your URL');
$imageTags = $doc->getElementsByTagName('img');

foreach($imageTags as $tag) {
$img_src= $tag->getAttribute('src');
}





By this we can get all the image tag in the particular URL, you can write separate scripts for Image types too.

Friday 12 July 2013

Search lists from Youtube, Dailymotion, Google and Metacafe using PHP

Youtube:  For youtube you need to down the files from google-api-php-client and please use this below demo file


$htmlBody = <<

 

    Search Term:
 
 

    Max Results:
 
 

END;

if ($_GET['q'] && $_GET['maxResults']) {
  // Call set_include_path() as needed to point to your client library.
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_YouTubeService.php';

  /* Set $DEVELOPER_KEY to the "API key" value from the "Access" tab of the
  Google APIs Console
  Please ensure that you have enabled the YouTube Data API for your project. */
  $DEVELOPER_KEY = 'put your api key here';

  $client = new Google_Client();
  $client->setDeveloperKey($DEVELOPER_KEY);

  $youtube = new Google_YoutubeService($client);

  try {
    $searchResponse = $youtube->search->listSearch('id,snippet', array(
      'q' => $_GET['q'],
      'maxResults' => $_GET['maxResults'],
    ));

    $videos = '';
    $channels = '';
    $playlists = '';


//print_r($searchResponse['items']);



for($x=0;$x
echo $searchResponse['items'][$x]['id'] ['videoId'] ;


}

/*
    foreach ($searchResponse['items'] as $searchResult) {
      switch ($searchResult['id']['kind']) {
        case 'youtube#video':
          $videos .= sprintf('

  • %s (%s)
  • ', $searchResult['snippet']['title'],
                $searchResult['id']['videoId']);
              break;
            case 'youtube#channel':
              $channels .= sprintf('
  • %s (%s)
  • ', $searchResult['snippet']['title'],
                $searchResult['id']['channelId']);
              break;
            case 'youtube#playlist':
              $playlists .= sprintf('
  • %s (%s)
  • ', $searchResult['snippet']['title'],
                $searchResult['id']['playlistId']);
              break;
          }
        }

        $htmlBody .= <<   

    Videos

       
      $videos


       

    Channels


       
      $channels

       

    Playlists


       
      $playlists

    END;*/
      } catch (Google_ServiceException $e) {
        $htmlBody .= sprintf('A service error occurred: %s
    ',
          htmlspecialchars($e->getMessage()));
      } catch (Google_Exception $e) {
        $htmlBody .= sprintf('An client error occurred: %s
    ',
          htmlspecialchars($e->getMessage()));
      }
    }
    ?>



     
        YouTube Search
     

     
       
     



    =================================================================

    Google Image Search:



    $url = "https://ajax.googleapis.com/ajax/services/search/images?" .
           "v=1.0&q=barack%20obama&userip=INSERT-USER-IP";

    // sendRequest
    // note how referer is set manually
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, "http://localhost/#######/google.php");
    $body = curl_exec($ch);
    curl_close($ch);

    // now, process the JSON string
    $json = json_decode($body);

    /*$results = array();
    foreach ($json['responseData']['results'] as $result) {
      $results[] = array(
        'url' => $result['url'],
        'title' => $result['title'],
        'content'=>$result['content']
      );
    }
    */
    echo '
    ';
    
    var_dump($json->responseData->results);
    echo '
    ';


    for($x=0;$xresponseData->results);$x++){

    echo "Result ".($x+1)."";
    echo "
    Image: ";
    echo $json->responseData->results[$x]->url;
    echo "


    echo $json->responseData->results[$x]->url;
    echo "
    URL: ";
    echo $json->responseData->results[$x]->url;
    echo "
    VisibleURL: ";
    echo $json->responseData->results[$x]->visibleUrl;
    echo "
    Title: ";
    echo $json->responseData->results[$x]->title;
    echo "
    Content: ";
    echo $json->responseData->results[$x]->content;
    echo "

    ";

    }

    // now have some fun with the results...

    /*echo '

    ';
    var_dump($json);
    echo '
    ';
    */


    //$decodedJSON = json_encode($json);

    // Put everyting to the screen with var_dump;
    //var_dump($decodedJSON);

    // With print_r ( useful for arrays );
    //print_r($decodedJSON);

    /*foreach ( $json->responseData->results as $results1 )
    {
           echo $results1;
    }*/

    //print_r($json->responseData->results);

    /*$properties = get_object_vars($json);
    print_r($properties);*/

    //print_r($json);

    ?>


    ==================================================================

    Metacafe:



    if(isset($_POST['search']))
    {
        $video=$_POST['video'];
        //echo $video;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'http://www.metacafe.com/topics/'.$video);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION,true);
        $result = curl_exec($curl); curl_close($curl);
        //echo $result;
       
        //$value=preg_match_all('/<section class=\"CCol">(.*?)<\/section>/s',$result,PREG_PATTERN_ORDER);
        preg_match('/
    (.*?)<\/section>/s', $result, $matches, PREG_OFFSET_CAPTURE);
        print_r($matches);
    }
    ?>
    http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd

    ">
    http://www.w3.org/1999/xhtml">


    Search Video - Metcafe




    ==================================================================

    Daily Motion:


    $url="https://api.dailymotion.com/videos?search=facebook&fields=id,title,channel,thumbnail_medium_url";
    // sendRequest
    // note how referer is set manually
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, "http://localhost/jothirajan/demos/dailymotion-sdk-php-master/test.php");

    $body = curl_exec($ch);
    curl_close($ch);

    // now, process the JSON string
    $json = json_decode($body);

    /*echo '
    ';
    var_dump($json);
    echo '
    ';

    */
    for($x=0;$xlist);$x++){


    echo "Result ".($x+1)."";
    echo "
    id: ";
    echo $json->list[$x]->id;
    echo "
    Img: ";
    echo "
    ";

    echo "
    channel: ";
    echo $json->list[$x]->channel;
    echo "
    title: ";
    echo $json->list[$x]->title;

    echo "

    ";

    }

    ?>





    Thursday 2 May 2013

    Increment date using while loop in php



     $start_date = "2013-01-01";
      $end_date = "2013-01-20";
      $next_date = $start_date;

      while(strtotime($next_date) <= strtotime($end_date))
      {
        echo "$next_date
    ";
        $next_date = date ("Y-m-d", strtotime("+5 day", strtotime($next_date)));
      }


    Ok in for loop?


    $start_date = "2013-01-01";
    $end_date = "2013-01-25";
    $next_date = $start_date;

    for($i=0;$i<=(strtotime($next_date) <= strtotime($end_date));$i++)
    {
    echo "$next_date
    ";
    $next_date = date ("Y-m-d", strtotime("+2 day", strtotime($next_date)));
    }





    SUM TWO TIMES IN PHP, SUM TWO TIME VALUES IN PHP

    echo sum_the_time('01:45:22', '17:27:03');

    function sum_the_time($time1, $time2) {
      $times = array($time1, $time2);
      $seconds = 0;
      foreach ($times as $time)
      {
        list($hour,$minute,$second) = explode(':', $time);
        $seconds += $hour*3600;
        $seconds += $minute*60;
        $seconds += $second;
      }
      $hours = floor($seconds/3600);
      $seconds -= $hours*3600;
      $minutes  = floor($seconds/60);
      $seconds -= $minutes*60;
      // return "{$hours}:{$minutes}:{$seconds}";
      return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);


    Thursday 14 March 2013

    Phonegap photoswipe with download option script



    (function(window, PhotoSwipe){

    document.addEventListener('DOMContentLoaded', function(){

    var
    options = {

    getImageCaption: function(el){

    var captionText, captionEl, captionTextSRC;

    // Get the caption from the alt tag
    if (el.nodeName === "IMG"){
    captionText = el.getAttribute('alt');
    captionTextSRC = el.getAttribute("src");
    }
    var i, j, childEl;
    for (i=0, j=el.childNodes.length; i childEl = el.childNodes[i];
    if (el.childNodes[i].nodeName === 'IMG'){
    captionText = childEl.getAttribute('alt');
    captionTextSRC = childEl.getAttribute("src");
    }
    }




    // Return a DOM element with custom styling
    captionEl = document.createElement('div');
    captionEl.style.cssText = 'background: red; font-weight: bold; padding: 5px;';
    captionEl.appendChild(document.createTextNode("Download"));
    //console.log('JJJJJJJJJJJJ'+ captionTextSRC);
    //captionEl.onclick = testing;
    //var fileTransfer = new FileTransfer();
    captionEl.onclick = (function() {
    //navigator.notification.alert("Loasdasdsaddsdsdsdgin Successfull");
    var fileTransfer = new FileTransfer();
    fileTransfer.download(
        captionTextSRC,
        "file://sdcard/"+captionText,
        function(entry) {
           navigator.notification.alert("download complete: " + entry.fullPath);
        },
        function(error) {
           navigator.notification.alert("download error source " + error.source);
            navigator.notification.alert("download error target " + error.target);
            navigator.notification.alert("upload error code" + error.code);
        });

    });


    //captionEl.appendChild(document.createTextNode(captionText));
    return captionEl;

    // Alternatively you can just pass back a string. However, any HTML
    // markup will be escaped

    }

    },
    instance = PhotoSwipe.attach( window.document.querySelectorAll('#Gallery a'), options );

    }, false);


    }(window, window.Code.PhotoSwipe));


    function testing()
    {
    navigator.notification.alert("Login Successfull");
    }

    Wednesday 13 March 2013

    SVN: Authorisation Failed

    Use the below command: rm ~/.gnome2/keyrings/login.keyring