如何使用PHP

时间:2018-09-20 02:30:29

标签: php

我正在从.txt文件中提取数据行,并尝试将其插入HTML表中。现在,我被困在输出数组上。通过重新爆炸,我能够将爆炸的线变成数组。我var_dumped新行,以确保它是一个数组。我需要返回一个将数据输出到HTML表中的函数。我不知道从这里去哪里。任何帮助表示赞赏。据我所知。对于示例,.txt文件中大约有10本书。是否在同一函数中包含HTML?还是外部,我该如何实施?谢谢。

PHP

function displayTable($filename)
{


 $table = "\n<table border='1'>";
           $table .= "<tr>";
           $table .= "<th>Title</th>";
           $table .= "<th>Author</th>";
           $table .= "<th>ISBN</th>";
           $table .= "<th>City</th>";
           $table .= "</tr>\n\n";

        $line_ctr = 0;

        $fp = fopen($filename, 'r');   //op

ens the file for reading

    if ($fp)
    {
        while(true)
        {

            $line = fgets($fp);

            if (feof($fp))
            {
                break;


    }

    $line_ctr++;

    //Explode into string
list($title, $author, $isbn, $city) = explode('*', $line);
$new_line = explode('*', $line);

var_dump($new_line);
}

    fclose($fp ); //Close file
}

当前输出样本

array(5) { [0]=> string(14) "Smart Living" [1]=> string(7) "health" [2]=> string(10) "2005-09-12" [3]=> string(13) "1-4145-5896-x" [4]=> string(2) " " } 

 array(5) { [0]=> string(14) "Make Money Sleeping" [1]=> string(7) "health" [2]=> string(10) "2009-01-08" [3]=> string(13) "1-4888-5896-x" [4]=> string(2) " " } 

2 个答案:

答案 0 :(得分:0)

我看到了您的通信网络。您想对表格进行排序。希望我已经重写了此功能,以帮助您。

您可以将其分为3个步骤:1.读取文件,2.sort数据,3。输出HTML。

function displayTable($filename)
{
    // 1. read file to array
    $data = array(); // Save all data read from txt file.
    $fp   = fopen($filename, 'r'); //opens the file for reading
    if ($fp) {
        while (true) {
            $line = fgets($fp);
            if (feof($fp)) {
                break;
            }
            $new_line = explode('*', $line);
            $data[]   = $new_line; // save to data
        }
        fclose($fp); //Close file
    }

    // 2. sort data, example for sort by ISBN
    if ($data) {
        foreach ($data as $key => $value) {
            $ISBN[$key] = $value[2]; //sort by ISBN
        }
        array_multisort($ISBN, SORT_ASC, $data);
    }

    // 3. output to HTML
    $table = "\n<table border='1'>";
    $table .= "<tr>";
    $table .= "<th>Title</th>";
    $table .= "<th>Author</th>";
    $table .= "<th>ISBN</th>";
    $table .= "<th>City</th>";
    $table .= "</tr>\n\n";
    foreach ($data as $key => $value) {
        $table .= "<tr><td>" . join("</td><td>", $value) . "</td></tr>";
    }
    $table .= "</table>";
    return $table;
}

答案 1 :(得分:-1)

    $new_line = explode('*', $line);
    $table .= "<tr><td>" . join("</td><td>", $new_line) . "</td></tr>";
}


return $table;