【问题标题】:Foreach only outputs last itemForeach 只输出最后一项
【发布时间】:2012-07-27 00:55:35
【问题描述】:

我正在尝试使用 foreach 将结果保存到文件中,但它只写入数组的最后一个结果。

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

注释的 echo 起作用并显示所有结果, fwrite 只将最后一个写入文件。有什么问题?

【问题讨论】:

  • HTML 代码是什么?也许 'a.bnone' 只选择最后一个元素,而不是全部。

标签: loops foreach fwrite


【解决方案1】:

您需要在 for each 周围放置花括号,因为您有两个语句,但只有第一个在 foreach 中循环,因此最后一个元素放入 $stringDatafwrite 函数仅调用一次。

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

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

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 1970-01-01
    • 2012-02-10
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 2015-02-26
    相关资源
    最近更新 更多