Extract URL Data Like Facebook Using PHP,jQuery And Ajax.

Friday, Apr 7, 2017

Tags:- PHP jQuery Ajax


URL Data like Title,Description and a default Image is very important to describe the URL. Many big websites like Facebook,Twitter used to extract the URL data whenever someone types the URL in textbox they extract all the details of the URL like Title,Description and a default Image so that other user easily know what that URL is all about.In this tutorial we going to tell how to extract the URL data using PHP,jQuery,Ajax.You may also like login with facebook using PHP.


Extract URL Data


To Extract URL Data it takes only Three steps:-

  1. Make a HTML file and define markup and script to Extract Data
  2. Make a PHP file to extract and send the data
  3. Make a CSS file and define styling for Extracted Data


Step 1.Make a HTML file and define markup and script to Extract Data

We make a HTML file and save it with a name extract.html

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="extract_style.css">
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript">
    function extracturl()
	{
	  var val=document.getElementById("url").value;
	  if(val!="" && val.indexOf("://")>-1)
	  {
	    $('#output').text('loading...');
	    $.ajax({
          type:'post',
          url:'fetch_url.php',
          data:{
            link:val
          },
	      cache: false,
	      success:function(response) {
		    document.getElementById("output").innerHTML=response;
          }
        });
	   }
    }
</script>
  
</head>

<body>
  
<h1>Extract URL Data Like Facebook Using PHP,jQuery And Ajax</h1>
<div>
  <textarea id="url" placeholder="Enter Complete URL For eg, http://talkerscode.com" onkeyup="extracturl();">
  </textarea>
  <div id="output"></div>
</div>

</body>
</html>

In this step we made a function extracturl() to send the ajax request to fetch_url.php and get the dataand then display it.We use onkeyup event whenever the user enter any word that extracturl function calls and automatically display data.You may also like auto post on facebook using PHP.



Step 2.Make a PHP file to extract and send the data

We make a PHP file named fetch_url.php

<?php
if(isset($_POST["link"]))
{		
   $main_url=$_POST["link"];
   @$str = file_get_contents($main_url);


   // This Code Block is used to extract title
   if(strlen($str)>0)
   {
     $str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
     preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title);
   }
  

   // This Code block is used to extract description 
   $b =$main_url;
   @$url = parse_url( $b ) ;
   @$tags = get_meta_tags( $url['scheme'].'://'.$url['host'] );


   // This Code Block is used to extract any image 1st image of the webpage
   $dom = new domDocument;
   @$dom->loadHTML($str);
   $images = $dom->getElementsByTagName('img');
   foreach ($images as $image)
   {
     $l1=@parse_url($image->getAttribute('src'));
     if($l1['scheme'])
     {
	   $img[]=$image->getAttribute('src');
     }
     else
     {
	
     }
   }


   // This Code Block is used to extract og:image which facebook extracts from webpage it is also considered 
   // the default image of the webpage
   $d = new DomDocument();
   @$d->loadHTML($str);
   $xp = new domxpath($d);
   foreach ($xp->query("//meta[@property='og:image']") as $el)
   {
     $l2=parse_url($el->getAttribute("content"));
     if($l2['scheme'])
     {
	   $img2[]=$el->getAttribute("content");
     }
     else
     {
	
     }
   }
?>


   <a href="<?php echo $main_url;?>" target="_blank">
   <?php
   echo "<p id='title'>".$title[1]."</p>";
   ?>
   <br>
   <?php
   if($img2)
   {
      echo "<img src='".$img2[0]."'><br>";
   }
   else
   {
     echo "<img src='".$img[0]."'><br>";
   }
   echo "<p id='desc'>".$tags['description']."</p>";
   ?>
   </a>
   <?php

   exit();
}
?>

This is the main step of our tutorial.In this step we extract the URL data like Title,Description and og:image it is also known as the default image of the webpage and if it is not found in the webpage then we extract another first image with <img> tag.You may also like get facebook like, share and comment count using PHP.


We use Simple Regular Expression to extract the title.To extract the description we use parse_url() function of PHP and after that we use get_meta_tags() function to get the meta tags you can also extract keywords of the webpage in same way.


Next is we use DomDocument object and find the og:image and then we use parse_url function to extract the og:image content or url and in Next code block we use the same process to get the any first image present in the webpage to display if the og:image is not present.


And after that we display the title,description and image in a link that points out the URL entered by the user for testing.You may also like auto expanding textarea like facebook using JavaScript.



Step 3.Make a CSS file and define styling for Extracted Data

We make a CSS file and save it with name extract_style.css.

body
{
	background-color:#A9BCF5;
	font-family:helvetica;
	margin:0px auto;
	padding:0px;
	text-align:center;
	height:1000px;
}
h1
{
	text-align:center;
	color:#0B0B61;
	margin-top:50px;
	font-size:35px;
}
textarea
{
	width:500px;
	height:100px;
	border:1px solid silver;
	padding:10px;
	font-size:18px;
	font-family:helvetica;
	color:blue;
}
#output
{
margin-top:50px;
}
#output a
{
	
	width:500px;
	background-color:white;
	box-shadow:0px 0px 10px 0px silver;
	display:block;
	text-decoration:none;
	text-align:left;
	padding-top:5px;
	padding-bottom:5px;
	
}
#output a #title
{
	font-size:18px;
	color:#424242;
	font-weight:bold;
	padding-left:5px;
	margin:0px;
}
#output a img
{
	width:500px;
	height:250px;
}
#output a #desc
{
	font-size:18px;
	color:#424242;
	padding-left:5px;
	margin-top:10px;
}

Thats all, this is how to Extract URL Data using PHP,jQuery and Ajax.You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Join Us With Our 21000+ Subscribers And Get Our Latest Tutorials Update Via Email