显示目录中的图像和文本文件中的文本

时间:2014-11-24 23:48:22

标签: php

我当前的一个项目给了我一些麻烦。有问题的网页应该显示文本文件中的文本,后跟目录中的附带图像。

目前,输出为文本1,图像1,文本2,图像1,文本1,图像2,文本2,图像2

我的代码到目前为止:         

    foreach ($DirEntries as $Entry)
    {
        if((strcmp($Entry, '.') != 0) && (strcmp($Entry, '..') != 0))
        {

            $inputFile = fopen("imagelist.txt", "r");
            if ($inputFile) 
            {
                while (($line = fgets($inputFile)) !== false) 
                {
                    echo "Name, description, and file name:<br />" . $line."<br>";
                    echo "<img src=\"files/" . $Entry . "\" ><br /><br />\n";     
                }
            } 
            else 
            {
                echo "There was an error in the opening file";
            } 
            fclose($inputFile);

        }
    }
    closedir($DirOpen);                         
    ?>

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您的问题似乎是嵌套的while循环,因为您正在处理一对一的关系。

这应该可以解决您的问题:

$inputFile = fopen("imagelist.txt", "r");

// probably better to check for file readability before looping the directory items.
if (!$inputFile) {
    echo "There was an error in the opening file";
}
else {

    foreach ($DirEntries as $entry)
    {
        if($entry === '.' || $entry === '..')
        {
            continue; // using a continue helps keeps the code indentation levels down.
        }

        // assuming that each line corresponds to an image in the same order
        if (($line = fgets($inputFile)))
        {
            echo "Name, description, and file name:<br />" . $line."<br>";
            echo "<img src=\"files/" . $entry . "\" ><br /><br />\n";     
        } 
        else 
        {
            echo "Image '$entry' has no metadata";
        } 
    }

    fclose($inputFile);

}
closedir($DirOpen); 
祝你好运!