put all of the string result in foreach loop to one variable

时间:2016-08-31 18:29:49

标签: php foreach

here is my code :

include('simple_html_dom.php');

$html = file_get_html('http://www.exampel.com');

foreach($html->find('item') as $article) {

    $item['title'] = $article->find('title', 0)->innertext;
    $item['description'] = $article->find('description', 0)->innertext;
    $item['description2'] .= $item['title'] .' : '. $item['description'] .'<br>'; 
    $articles[] = $item;

}

echo $item['description2']; 

i use $item['description2'] .= to combine foreach result of $item['description']

echo worked but i got "Notice: Undefined index: description2"

What is the problem?

and how to put each of the loop result of $item['description'] to one variable.?

1 个答案:

答案 0 :(得分:1)

There is no $item['description2'] the first time php try to concat the string.

include('simple_html_dom.php');

$html = file_get_html('http://www.exampel.com');

foreach($html->find('item') as $article) {

    $item['title'] = $article->find('title', 0)->innertext;
    $item['description'] = $article->find('description', 0)->innertext;
    if (!isset($item['description2'])) {
        $item['description2'] = '';
    }
    $item['description2'] .= $item['title'] .' : '. $item['description'] .'<br>';
    $articles[] = $item;

}

echo $item['description2'];