PHP Foreach循环和DOMNodeList [英] PHP Foreach Loop and DOMNodeList
问题描述
我试图确定一个用DOMNodeList集合播种的foreach循环的结束。目前,我正在使用一个for循环,希望避免在那里有一个魔术号码。我知道只有8列,但我希望代码我通用的其他应用程序。
是否有可能将其转换为一个Foreach循环?我已经尝试了end()和next()函数,但是它们没有返回任何数据,我怀疑它们只能在数组上而不是这个DOMNodeList集合中。
该代码正在建立一个CSV文件,没有结尾的','
当前输出是:
$ b
值1 值2值3值4值5值6值7值8
< >以下是一个代码示例:
$ cols = $ row-> getElementsByTagName(td);
$ printData = true;
//丢掉标题行
if($ isFirst&& $ printData){
$ isFirst = false;
继续;
($ i = 0; $ i <= 8; $ i ++){
$ output = iconv(UTF-8,ASCII // IGNORE,$ cols-> item($ i) - > nodeValue);
$ output2 = trim($ output);
if($ i == 8){
//最后一列
echo\。$ output2。\。 \\\
;
} else {
echo\。$ output2。\。 ;
$ div $解析方案
可以使用:
$ cols->长度
检索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);
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 . "\"" . ",";
}
}
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);
这篇关于PHP Foreach循环和DOMNodeList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!