2010-01-06 91 views
1

我想确定一个foreach循环的结束与种子DOMNodeList的集合。目前,我使用for循环希望避免在那里有一个'魔术'数字。我知道只有8列,但我希望代码我通用于其他应用程序。PHP的Foreach循环和DOMNodeList

是否有可能将其转换为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 . "\"" . ","; 
    } 
} 

回答

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); 
1
$cols->length 

应该给你的数量在列表中

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

// ... 

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