Search code examples
loopsforeachfwrite

Foreach only outputs last item


I'm trying to use a foreach to save the results to a file but it only writes the last result of the array.

include_once('../simple_html_dom.php');
$myFile = "urls.txt";
$fh = fopen($myFile, 'a') or die("can't open file");

$html = file_get_html('the-url');

foreach($html->find('a.bnone') as $element) 

    $stringData = $element->href . '\n';
    fwrite($fh, $stringData);
        //echo $element->href . '<br>';

The commented echo works and displays all the results, the fwrite only writes the last one to the file. What is the problem?


Solution

  • You need to place curly braces around your for each because you have two statements in there but only the first is being looped in the foreach, the last element is thus put in $stringData and the fwrite function is only called once.

    foreach($html->find('a.bnone') as $element) {
    
        $stringData = $element->href . '\n';
        fwrite($fh, $stringData);
        //echo $element->href . '<br>';
    }