PHP Foreach循环和DOMNodeList

4
我正在尝试确定由DOMNodeList集合种子的foreach循环的结尾。目前,我正在使用for循环,并希望避免在那里使用“魔法”数字。我确实知道只会有8列,但我希望代码对其他应用程序也具有通用性。
是否可能将此转换为Foreach循环?我已经尝试了end()和next()函数,但它们没有返回任何数据,我怀疑它们只适用于数组而不是这个DOMNodeList集合。
该代码正在构建一个CSV文件,没有尾随的“,”。
当前输出为:
"Value 1","Value 2","Value 3","Value 4","Value 5","Value 6","Value 7","Value 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 . "\"" . ",";
   }
}
2个回答

5

您可以使用:

$cols->length

获取DOMNodeList中项目的数量。

请参见http://php.net/manual/en/class.domnodelist.php

编辑: 如果您将代码更改为以下内容,则无需担心尾随逗号或长度:

$output = array();
foreach ($cols as $item) {
   $output = iconv("UTF-8", "ASCII//IGNORE", $item->nodeValue);
   $output2 = trim($output);

   $output[] = '"' . $output2 . '"';
}
$outputstring = implode(',', $output);

2
$cols->length

应该给出列表中的项目数量。

for ($i = 0; $i < $cols->length; $i++) {

// ...

if ($i == $cols->length - 1) {
// last column

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接