PHP Foreach Loop and DOMNodeList

foreach, php

Solution

You can use:

$cols->length

To retrieve the number of items in a DOMNodeList.

See http://php.net/manual/en/class.domnodelist.php

Edit: If you change you're code to this, you don't have to worry about the trailing comma, or the length:

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

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

Problem

I am trying to determine the end of a foreach loop that is seeded with a collection of DOMNodeList. Currently, I am using a for loop would like to avoid having a 'magic' number there. I do know there are only going to be 8 columns, but I would like the code me generic for other applications. Is it possible to convert this to a Foreach loop? I have tried the end() and next() functions, but they are not returning any data and I suspect that they only work on arrays and not this DOMNodeList collection. The code is building a CSV file without the trailing ',' Current output is: "Value 1","Value 2","Value 3","Value 4","Value 5","Value 6","Value 7","Value 8" Here is an example of code: ``` $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 . "\"" . ","; } } ```

Original source