在PHP中将字符串CSV转换为HTML表

时间:2016-07-15 02:33:04

标签: php html csv html-table

我正在使用PHP&amp ;;制作一个小型金融市场小部件。 HTML。我想将以下CSV字符串转换为HTML表格

result=1&size=200 EURUSD;1.11143;1.11143;1.11170;1.11025;1468549348 CADJPY;82.333;82.345;82.382;81.411;1468549348 EURGBP;0.81374;0.81386;0.83144;0.77313;1466801995 CADCHF;0.76110;0.76110;0.76120;0.75957;1468549347

我在名为$ result的字符串中获得上述值。

如何显示标准HTML表格,如:

符号|出价|问|高|低|时间
EURUSD | 1.11143 | 1.11143 | 1.11170 | 1.11025 | 1468549348

依旧......

编辑:

尝试

$csvData = $result;
$lines = explode("\n", $csvData);
 echo "<table class='display' id='example'><thead >"; 
 echo "<tr class = 'even_gradeC'>
    <th class='history'><strong>Symbol</strong></th>
    <th class='history'><strong>Bid</strong></th>
    <th class='history'><strong>Ask</strong></th>
     <th class='history'><strong>High</strong></th>
    <th class='history'><strong>Low</strong></th>
    <th class='history'><strong>Time</strong></th>

    </tr>";
    echo "</thead>";    
 foreach ($lines as $line) 
{
$data = explode(';', $line );
if(count($data)==6) 
{
echo"<tr class='even_gradeC'>";
foreach($data as $row => $value)
{
if($row<>6)
//{
if ($row==1)
{
echo "<td align='right'>";
echo $value;
echo "</td>";

}
elseif ($row==2)
{
echo "<td>";
echo $value;
echo "</td>";
}
elseif ($row==3)
{
echo "<td>";
echo $value; 
echo "</td>";
}
elseif ($row==4)
{
echo "<td>";
echo $value; 
echo "</td>";
}

elseif ($row==5)
{
echo "<td>";
echo $value; 
echo "</td>";
}
elseif ($row==6)
{
echo "<td>";
echo $value; 
echo "</td>";

}
else
{
echo "<td>";
echo $value;
echo "</td>";
}
} 
echo "<td>";
echo $value;
echo "</td>"; 
} 
}
echo "</tr>";
echo "</table>";

1 个答案:

答案 0 :(得分:0)

$csvLines = explode("\n", $csvData); // or use space as delimiter

echo "<table><tbody>";

foreach ($csvLines as $line) {
    $lineData = explode(";", $line);

    if (6 != count($lineData)) {
        continue;
    }

    echo "<tr>";

    foreach ($lineData as $value) {
        echo "<td>" . $value . "</td>";
    }

    echo "</tr>";
}

echo "</tbody></table>";