When you post a link as Facebook update, the title and meta-description of the webpage is automatically retrieved and displayed. Here is an example,
The same thing happens in Digg when you submit a weblink.
So if you’re building a web application where you need to retrieve title, meta-description, meta-keywords or any other meta information of a webpage then read the following code carefully and the explanation below.
PHP code to get title, meta-description and meta-keywords
<?php $submitted="http://yourravi.com/get-title-meta-description-meta-keywords-webpage-from-url-weblink-php-code"; $urlContents = file_get_contents($submitted); $dom = new DOMDocument(); @$dom->loadHTML($urlContents); $titly = $dom->getElementsByTagName('title'); $title=$titly->item(0)->nodeValue; $metatagarray = get_meta_tags($submitted); $keywords = $metatagarray["keywords"]; $description = $metatagarray["description"]; echo "<strong>URL: </strong >$submitted <br/>"; echo "<strong>Title:</strong> $title <br/>"; echo "<strong>Description: </strong >$description <br/>"; echo "<strong>Keywords: </strong >$keywords <br/>"; ?>
- In the above written php code, we’re retrieving title, description and keywords for the link ‘http://yourravi.com/get-title-meta-description-meta-keywords-webpage-from-url-weblink-php-code’. You can use any url here. Optionally, you can also put a input box and ask user to provide a weblink. Then catch the entered url and display the title and meta information for it. This is exactly what happens in Facebook, Digg and other Web 2.0 sites.
- Next we retrieve the HTML code of the submitted url/weblink, and extract the title from it. For doing this, we use the DOMDocument php class and its few functions.
- Getting meta-description, keywords, author and meta information is very easy. For this we just have to use the ‘get_meta_tags()‘ function of php.
- Here we’re actually loading the entire HTML code, so displaying results would take some time [2-3 seconds].
[If there is any better/easy solution ,or any query, please mention in comments.]