简体   繁体   中英

Setting variable variables inside a foreach

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://something.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.something.com/term/'
     . ??? . '/0/feed');

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

Do I need another loop inside of the foreach? Any help is appreciated.

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.

Instead of using an array created with range, use a for loop as follows:

for($i = 100; $i <= 300; $i++){
     $feed = simplexml_load_file('http://www.something.com/term/' . $i . '/0/feed');
     echo 'Feed URL: <a href="http://something.com/term/' . $i . '/0/feed">http://www.something.com/term/' . $i . '/0/feed/</a> <br /> Feed category: ' . $feed->channel[0]->title . '<br/>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM