doulangbi6869 2012-03-31 06:28
浏览 9
已采纳

无法理解PHP代码示例

I've been looking around to see if anyone else has dissected this code already, but that has proven to be futile. I'm having some trouble understanding what's happening in this php code sample from here.

I'm still currently very new to programming and PHP as a whole so I'm hoping someone can give me a clean explanation (I have read the documentation, but I still fail to fully understand the code)

I'm currently tackling on a project to convert an uploaded CSV file into an array and then into a database. The sample code is below:

Example #1 Read and print the entire contents of a CSV file

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>
";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />
";
        }
    }
    fclose($handle);
}


?>

I guess my problem really is with understanding the fgetcsv method, but if someone could provide me with a breakdown it would really be appreciated.

  • 写回答

2条回答 默认 最新

  • douxun1407 2012-03-31 06:35
    关注

    $row = 1;

    Sets the initial number of rows processed.

    if (($handle = fopen("test.csv", "r")) !== FALSE) {

    Attempts to open the file (for reading only), continuing only if it can.

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

    Iterates over each line in the CSV (with a maximum length of the row being 1,000 characters and the field delimiter being a comma), continuing only if it can, pulling the row out as an indexed array of the fields.

    $num = count($data);

    Gets the number of fields in the row.

    echo "<p> $num fields in line $row: <br /></p> ";

    Outputs the number of fields in the given row.

    $row++;

    Increments the row number.

    for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br /> "; }

    Iterates over each field in the row and outputs its value.

    fclose($handle);

    Closes the file.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?