PHP CSV输出 - 如何添加两行?

时间:2017-06-27 14:09:22

标签: php csv

Hello分组!

Alessandro Minoccheri已经帮我解决了这个问题,但我还有一个问题。 CSV文件是powershell(get-aduser)的输出文件 - 它是逗号分隔的。

首先,这是csv内容:

#TYPE Selected.Microsoft.ActiveDirectory.Management.ADUser
name,"officephone"
firstname, lastname,"+49 1234 555 134"
firstname, lastname,"+49 1234 555 242"
firstname, lastname,"+49 1234 555 338"
firstname, lastname,"+49 1234 555 149"

这就是目前的代码:

$lineCount = 0;
while (($line = fgetcsv($f)) !== false) {
if ($lineCount > 1) {
    echo "<tr class='departmenttext'>";
    foreach ($line as $key => $cell) {
        if ($key == 1) {
           $cell = substr($cell, -3);
           echo '';
        }
        echo "<td>" . htmlspecialchars($cell) . "</td>";

        if ($key == 1) {
            echo "</tr>\n";
        }
    }
    echo "</tr>\n";
}
$lineCount = $lineCount + 1;
}

它在一行中显示一个CSV文件。装置

Name1 Phone1
Name2 Phone2
Name3 Phone3
Name4 Phone4

但由于有时很长,我需要以下内容:

Name1 Phone1    Name5 Phone5
Name2 Phone2    Name6 Phone6
Name3 Phone3    Name7 Phone7
Name4 Phone4

但是因为我只有一个导出函数“htmlspecialchars($ cell)我不知道如何分开它?”

3 个答案:

答案 0 :(得分:0)

First of all you have to decide that how much line you want in one bunch. and according to that number, You need to start a new raw in loop.

for example, if you want to show up to 10 line in one bunch, like

you need something like

if($key%10 == 0){
    echo "</tr><tr class='departmenttext'>";
    echo "<td>" . htmlspecialchars($cell) . "</td>";
}

答案 1 :(得分:0)

很难像你想的那样包装文件,但另一种方法是将条目并排放置......

$lineCount = 0;
fgetcsv($f);
fgetcsv($f);
while (($line = fgetcsv($f)) !== false) {
    if ( count($line)<2 )   {
        break;
    }
    if ($lineCount % 2 == 0) {
        echo "<tr class='departmenttext'>";
    }
    echo "<td>" . htmlspecialchars($line[0].','.$line[1]) . "</td>";
    echo "<td>" . htmlspecialchars(substr($line[2],-3)) . "</td>";

    if ($lineCount % 2 == 1) {
        echo "</tr>\n";
    }
    $lineCount = $lineCount + 1;
}
if ($lineCount % 2 == 1) {
    echo "</tr>\n";
}

答案 2 :(得分:0)

You can do something like this way

if($key%count($line) == 0){
    echo "</tr><tr class='departmenttext'>";
    echo "<td>" . htmlspecialchars($cell) . "</td>";
}

Here I have divided it by total number of line so that it can be calculate 50% of your line.