简体   繁体   English

在foreach中设置变量变量

[英]Setting variable variables inside a foreach

I am trying to use $value inside the $feed_title variable. 我试图在$ feed_title变量中使用$ value。 And generate all 200 $feed_title variables. 并生成所有200个$ feed_title变量。

What I am trying to accomplish would look like this: 我要完成的工作看起来像这样:

Feed Url : http://something.com/term/###/feed Feed Title : Some Title Feed网址http//something.com/term/###/feed Feed标题 :某些标题

Where the ### varies from 100-300. ###的范围是100-300。

I am using the following code, and getting the urls, but not sure how to get the titles for each feed: 我正在使用以下代码,并获取url,但不确定如何获取每个供稿的标题:

$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? 我是否需要在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. 这是从translate.com页面获得标题的。 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. 如果要从xml获取标题,只需将getTitle更改为函数即可。

Instead of using an array created with range, use a for loop as follows: 代替使用使用range创建的数组,请使用如下所示的for循环:

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/>';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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