开发者

PHP Foreach Loop and DOMNodeList Collection [duplicate]

This question already has answers here: PHP Foreach Loop and DOMNodeList (2 answers) Closed 9 years ago.

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); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜