PHP Foreach Loop and DOMNodeList Collection [duplicate]
I am trying to see if I can convert a for loop to a foreach loop. Reason: Because I would like to make this code more generic and stay away from magic numbers. Although I开发者_开发知识库 know the numbers of column in the dataset, I would prefer to make the code more generic. I have tried using the end() and next() functions to try and detect the last element in the DOMNodeList, but I am not having success.
My final output will be in a CSV format with enclosures like so,
"Value 1","Value 2","Value 3","Value 4","Value 5","Value 6","Value 7","Value 8"
Here is my original for loop:
$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 . "\"" . ",";
}
}
Below is an example of how you might do it with a foreach. Although you can always use $cols->length
to get the number of nodes in the list which would also solve your problem using a for loop.
// 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);
精彩评论