如何在Array中转换CSV文件的表值?

时间:2016-10-13 10:57:30

标签: php arrays csv html-table customization

我的我的CSV文件的第一列

的值低于此值
<table border="1">
<tr>
    <th align="left">First Name</th>
    <th align="left">Gender</th>
    <th align="left">Nationality</th>
</tr>
<tr>
    <td align="left">Mike</td>
    <td align="left">M</td>
    <td align="left">Singaporean</td>
</tr>

我已经关注:Read each line of txt file to new array element

如何将上述CSV文件转换为Array。所以输出将是

Array
(
    [0] => Array
        (
            [0] => First Name
            [1] => Gender
            [2] => Nationality
        )

    [1] => Array
        (
            [0] => Mike
            [1] => M
            [2] => Singaporean
        )
)

3 个答案:

答案 0 :(得分:1)

使用DOMDocument::saveHTML

对PHP数组进行HTML表示

参考此示例代码:

$htmlString = '
    <td align="left">Mike</td>
    <td align="left">M</td>
    <td align="left">Singaporean</td>
';

$dom = new DOMDocument;
$dom->loadHTML($htmlString);
foreach($dom->getElementsByTagName('td') as $node)
{
    $arrayTd[] = $dom->saveHTML($node);
}

print_r($arrayTd);

答案 1 :(得分:0)

您也可以使用任何csv阅读库。例如这一个 - http://csv.thephpleague.com/basic-usage/。通过库进行操作将非常容易

答案 2 :(得分:0)

你需要使用folde和location作为param来选择文件,你可以使用simpleExcel lib来解析这样的CSV

function parseCSV($location,$folder){
    $excel = new SimpleExcel('CSV');

    try{
      $csv=$excel->parser->loadFile($location);
    }catch (Exception $ex){
      $logger->info($ex->getMessage());
    }

    $j = 1;
    /****column name ****/
    if($excel->parser->isRowExists($j)){
        $cols = $excel->parser->getRow($j);
    }

    $i=2;
    $arrval = array();
    /***csv data****/
    while($excel->parser->isRowExists($i)){
        $data=$excel->parser->getRow($i);
    }
}

使用此函数并传递必需的参数然后执行var_dump($ cols)和var_dump($ data)。这没有经过测试但会起作用