phpurlextractdigg

how to extract a url's title, images, keywords and description using php?


Possible Duplicate:
Fastest way to retrieve a <title> in PHP

Suppose there is a website http://www.example.com with title = "Example" description = "it is an example" and keywords = "example, question, love php".

What will be the php code or any other code with which these can be fetched on submission of the link?


Solution

  • If you would like to fetch the data from an external link you want to get the page using curl.

    Here's an example

    <?php
    $ch = curl_init("http://www.google.nl");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    curl_close($ch);
    
    $title = preg_match('!<title>(.*?)</title>!i', $result, $matches) ? $matches[1] : 'No title found';
    $description = preg_match('!<meta name="description" content="(.*?)">!i', $result, $matches) ? $matches[1] : 'No meta description found';
    $keywords = preg_match('!<meta name="keywords" content="(.*?)">!i', $result, $matches) ? $matches[1] : 'No meta keywords found';
    
    echo $title . '<br>';
    echo $description . '<br>';
    echo $keywords . '<br>';
    ?>
    

    For google.nl this returns:

    Google
    No meta description found
    No meta keywords found
    

    The meta description and keywords might need more tweaking for your use.

    Little sidenote cURL is not installed by default in apache so you might need to install if first.

    Here's the cURL php function page: https://www.php.net/manual/en/ref.curl.php