PHP Foreach循环和DOMNodeList集合

时间:2010-01-07 03:38:32

标签: php foreach

我试图看看是否可以将for循环转换为foreach循环。原因:因为我想使这个代码更通用,并远离魔术数字。虽然我知道数据集中的列数,但我更希望使代码更通用。我尝试使用end()和next()函数来尝试检测DOMNodeList中的最后一个元素,但我没有成功。

我的最终输出将采用CSV格式,其中包含类似的内容,

“值1”,“值2”,“值3”,“值4”,“值5”,“值6”,“值7”,“值8”

这是我原来的循环:

  $cols = $row->getElementsByTagName("td");
  $printData = true;
  // Throw away the header row
  if ($isFirst && $printData) {
     $isFirst = false;
     continue;
  }

  for ($i = 0; $i <= 8; $i++) {
     $output = iconv("UTF-8", "ASCII//IGNORE", $cols->item($i)->nodeValue);
     $output2 = trim($output);

     if ($i == 8) {
        // Last Column
        echo "\"" . $output2 . "\"" . "\n";
     } else {
        echo "\"" . $output2 . "\"" . ",";
     }
  }

1 个答案:

答案 0 :(得分:2)

以下是您如何使用foreach执行此操作的示例。虽然您始终可以使用$cols->length来获取列表中的节点数,这也可以使用for循环来解决您的问题。

 // assume there is an array initialized called outside of the loop for the rows called $lines
  $cols = $row->getElementsByTagName("td");

  $row = array();
  foreach($cols as $item)
  {
    $raw = $item->nodeValue;
    $row[] = '"'.trim(iconv("UTF-8", "ASCII//IGNORE", $raw)).'"';

  }
  $lines[] = implode(',', $row); // turn the array into a line

  // this is outside the loop for rows
  $output = implode("\n", $lines);