Search code examples
phpmeta

How to extract meta tags from website?


I'm currently using get_meta_tags to get the tags from a variety of websites like this:

<?php $tags = get_meta_tags('http://www.stackoverflow.com/'); ?>

This is the code I'm using to display that information:

<?php echo $tags['description']; ?><br /><br />
<?php echo $tags['keywords']; ?>

Now there are two things I can't figure out how to do:

  1. How do I make it so that <br /><br /> is removed if the meta description doesn't exist? Basically do that there isn't extra lines at the top causing an empty spot.

  2. How can I make the keywords all links to my domain such as http://mysite.com/keyword/coding``http://mysite.com/keyword/website-builder or http://mysite.com/keyword/php-help?


Solution

  • This should do the trick:

    <?php
    
    $tags = get_meta_tags('http://www.ebay.com/');
    
    if(trim($tags['description'])!='') //if description is set and not empty
    {
        echo ($tags['description']).'<br /><br />';
    }
    
    echo $tags['keywords'];
    
    $keywordArray = explode(",", $tags['keywords']); //split string with keywords in an array
    foreach($keywordArray as $keyword) //for each entry in the array
    {
        echo "http://www.mysite.com/".urlencode(trim($keyword)); //echo your URL. Encode the keyword in case special chars are present
    }
    
    ?>
    

    Akam gave you the short notation of the if-statement, I personally prefer the long notation.