PHP嵌套文本文件列表

时间:2015-12-10 19:58:16

标签: php file

我有textfile“animals.txt”,它看起来像:

mammals     cat, fox, horse
birds       parrot, eagle
reptiles    snake, crocodile

列由\t,分隔。

如何将其显示为嵌套列表,如下所示:

<ul>
        <li>mammals
            <ul>
                <li>cat</li>
                <li>fox</li>
                <li>horse</li>
            </ul>
        </li>
        <li>birds
            <ul>
                <li>parrot</li>
                <li>eagle</li>
            </ul>

        </li>
        <li>reptiles
            <ul>
                <li>snake</li>
                <li>crocodile</li>
            </ul>
        </li>
    </ul>

我现在拥有的:

$data = file_get_contents('animals.txt');
$array = explode("\t", $data);
foreach ($array as $line) {
    echo "<li>$line</li>";
}

2 个答案:

答案 0 :(得分:0)

这会奏效。爆炸每一行,然后打印相应的ul和li:

$file = file('animals.txt');

print '<ul>';

foreach ($file as $line) {

    // 1) exploding by "\t" and then again by ","
    $values = explode("\t", $line);
    $list = explode(',', $values[1]);

    // 2) show the first name in the line
    print '<li>';   
    print $values[0];
    print '<ul>';

    // 3) followed by a nested ul containing the comma-separated values
    foreach ($list as $sub_item) {  
        print '<li>' . $sub_item . '</li>'; 
    }

    print '</ul>';  
    print '</li>';
}

print '</ul>';

答案 1 :(得分:-1)

这会奏效。第一步是分隔制表符分隔的值(哺乳动物猫,狐狸,马)和第二步(foreach循环)是获得逗号分隔值(猫,狐狸,马)。最后,我们在列表中打印单个值(猫狐等)。

    def processFormData(data: MultipartFormData) = {
        var attForm = ""
        val bodyPart = data.fields(0)

        data.fields foreach {
            bodyPart => println(bodyPart.headers.find(h=> h.is("content-disposition")).get.value)
        }

    }