Question

I have a list of links that are all articles. I am trying to use PHP to extract the title and the description from all of them at once. I also want the article title to be hyperlink to the URL and the description to be displayed below it in italics.

My issue is this: it works when I do it for one link, but when I try multiple links or even if I duplicate the code and manually paste in each link, it doesn't work. Below is my code that I have that works for one link. Any ideas?

    <html>
    <a href="http://bit.ly/18EFx87">
    <b><?php

    function getTitle($Url){
        $str = file_get_contents($Url);
        if(strlen($str)>0){
            preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
            return $title[1];
        }
    }
    echo getTitle("http://bit.ly/18EFx87");

    ?></b><br>
    </a>
    <i><?php
    $tags = get_meta_tags('http://bit.ly/18EFx87');
    echo $tags['description'];
    ?></i>
    </html>
Was it helpful?

Solution

I assume you mean multiple URLs, then something like this will work. :

<html>

<?php
function getTitle($url){
    @$str = file_get_contents($url); // suppressing the warning
    if(strlen($str)>0){
        preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
        return $title[1];
    } else {
        return false;
    }
}

$urls = array('http://bit.ly/18EFx87', 'url2');
foreach($urls as $url)
{
    $title = getTitle($url);
    if($title === false)
    {
        continue;
    }
    echo '<a href="' . $url . '"><b>';
    echo $title;

    echo '</b></a><br><i>';

    $tags = get_meta_tags($url);
    echo $tags['description'] . '</i>';
 } 
 ?>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top