In facebook, when you paste or tyep a url, it automatically extracts the contents from the url with images if any. Same thing i do myself in php.
Basically facebook use open graph meta tags for extracts contents. Meta tags like
<meta property="og:title" content="" />, <meta property="og:description" content="" />, <meta property="og:img" content="" />, <meta property="og:url" content="" />.
To get meta tags information First i get html from url using file_get_contents() function. Then load html using DOMDocument class. Using DOMDocument you can get meta tags information easily.
For Demo : Click Here
<?php
if($_POST)
{
$url = $_POST['url']; // Give url here.
$desc = ""; $img = ""; $title = ""; $main_url = "";
$response = file_get_contents($url);
$doc=new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($response);
libxml_clear_errors();
$xml=simplexml_import_dom($doc); // just to make xpath more simple
$metas=$xml->xpath('//meta');
foreach ($metas as $meta) {
if($meta['property'] == "og:image") {
$img = $meta['content'];
}
else if($meta['property'] == "og:description")
{
$desc = $meta['content'];
}
else if($meta['name'] == "description")
{
$desc = $meta['content'];
}
else if($meta['property'] == "og:title")
{
$title = $meta['content'];
}
else if($meta['property'] == "og:url")
{
$url_main = $meta['content'];
}
}
if($title == "")
{
$t = $xml->xpath('//title');
foreach ($t as $key => $value)
{
$title = $value[0];
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Get site description from the given url</title>
</head>
<body>
<form method="post">
Enter URL : <input type="text" name="url" size="50"/>
<br />
<br />
<input type="submit" name="submit" Value="Submit" />
</form>
<br />
<?php
if ($_POST)
{
?> <div class="site-desc" style="width:40%;">
<div class="site-img" style="float:left;">
<img width="150" height="150" src="<?php echo $img; ?>" />
</div>
<div class="site-content" style="margin-left: 160px;">
<a class="sute-url" href="<?php echo $main_url != "" ? $main_url : $url; ?>"> <?php echo $title; ?> </a>
<br />
<p class="short-desc">
<?php echo $desc; ?>
</p>
</div>
</div>
<?php
}
?>
</body>
</html>
0 comments:
Post a Comment