phploopshtml-parsing

Fetch the title text from an external webpage via dynamic URL


I am trying to use $value inside the $feed_title variable. And generate all 200 $feed_title variables.

What I am trying to accomplish would look like this:

Feed Url: http://example.com/term/###/feed
Feed Title: Some Title

Where the ### varies from 100-300.

I am using the following code, and getting the urls, but not sure how to get the titles for each feed:

$arr = range(100,300); 

foreach ($arr as $key => $value) 
{ 
    unset($arr[$key + 1]);

    $feed_title = simplexml_load_file('http://www.example.com/term/'
     . ??? . '/0/feed');

    echo 'Feed URL: <a href="http://www.example.com/term/' . $value 
     . '/0/feed">http://www.example.com//term/' . $value 
     . '/0/feed</a><br/>  Feed Category: ' . $feed_title->channel[0]->title
     . '<br/>';
} 

Do I need another loop inside of the foreach?


Solution

  • If you want to get the title of a page, use this function:

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

    Here's some sample code:

    <?php
    function getTitle($Url){
        $str = file_get_contents($Url);
        if(strlen($str)>0){
            preg_match("/\<title\>(.*)\<\/title\>/",$str,$title);
            return $title[1];
        }
    }
    
    $arr = range(300,305); 
    foreach($arr as $value) 
    { 
    
        $feed_title = getTitle('http://www.translate.com/portuguese/feed/' . $value);
    
        echo 'Feed URL: <a href="http://www.translate.com/portuguese/feed/' . $value . '">http://www.translate.com/portuguese/feed/' . $value . '</a><br/>
              Feed Category: ' . $feed_title . '<br/>';
    
    
    }
    ?>
    

    This gets the title from translate.com pages. I just limited the number of pages for faster execution.

    Just change the getTitle to your function if you want to get the title from xml.