How to convert CSV file's table values in Array?

一笑奈何 提交于 2019-12-10 11:05:33

问题


I have below value in 1st Column of My CSV file

<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>

I already followed: Read each line of txt file to new array element

How to convert above CSV file to Array. So output will be

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

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

回答1:


HTML representation to php array using DOMDocument::saveHTML

Refer this example code:

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



回答2:


You can use any csv reading library also. For example this one - http://csv.thephpleague.com/basic-usage/ . the manipulation through libraries will be very easy




回答3:


you need the folde and location as param to pick the file and you can use simpleExcel lib for parsing CSV like this

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

use this function and pass required param then do var_dump($cols) and var_dump($data). this is not tested but will work



来源:https://stackoverflow.com/questions/40019093/how-to-convert-csv-files-table-values-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!