简体   繁体   English

如何使用php获取文本文件中的图像名称?

[英]how can I get the image names that are inside a text file with php?

Like always, I am having issues doing this.像往常一样,我在这样做时遇到了问题。 So, I have been able to extract images from folders using php, but since it was taking too long to do that, I decided to just extract the names from a text file and then do a while loop and echo the list of results.所以,我已经能够使用 php 从文件夹中提取图像,但由于这样做需要很长时间,我决定只从文本文件中提取名称,然后执行 while 循环并回显结果列表。 For example I have a file called, "cats.txt" and inside the data looks like this.例如,我有一个名为“cats.txt”的文件,其中的数据如下所示。

Kitten1.jpg
Kitten2.jpg
Kitten3.jpg

I could easily use an sql or json table to do this, but I am not allowed.我可以轻松地使用 sql 或 json 表来执行此操作,但不允许这样做。 So, I only have this.所以,我只有这个。

Now, I have tried doing this, but I get an error.现在,我尝试这样做,但出现错误。

--- PHP CODE --- --- PHP 代码 ---

$data = file ("path/to/the/file/cats.txt");
for ($i = 0; $i < count ($data); i++){
 $images = '<img src="/kittens/t/$i">';
}

$CatLife = '
Images of our kittens:<br>

'.$images.'


';

I would really appreciate the help.我真的很感激你的帮助。 I am not sure of what the error is, since the page doesn't tell me anything.我不确定错误是什么,因为该页面没有告诉我任何信息。 It just doesn't load.它只是不加载。

You can try something like this:你可以尝试这样的事情:

$fp = fopen('path/to/the/file/cats.txt', 'r');
$images = '';
while(!feof($fp)) {
     $row = fgets($fp);
     $images .= '<img src="/kittens/t/'.$row.'">';
}
fclose($fp);

$CatLife = "Images of our kittens:<br>$images";

Get used to foreach() .习惯foreach() Much easier.容易多了。 Also note that variables like $file in your img tag don't get interpreted in single quotes.另请注意, img标签中的$file等变量不会用单引号解释。 I use an array and then implode it:我使用一个数组,然后内爆它:

$data = file ("path/to/the/file/cats.txt");
foreach($data as $file) {
    $images[] = '<img src="/kittens/t/'.$file.'">';
}

$CatLife = '
Images of our kittens:<br>

'.implode($images).'


';

You could also just use $images .= '<img src="/kittens/t/$file">';你也可以只使用$images .= '<img src="/kittens/t/$file">'; to concatenate and not need to implode.连接而不需要内爆。

Maybe you should use the glob php function instead of parsing your txt file.也许您应该使用 glob php 函数而不是解析您的 txt 文件。

foreach (glob("path/to/the/file/Kitten*.jpg") as $filename) {
    echo "$filename\n";
}
    $data = file ("path/to/the/file/cats.txt");
    $images = '';
    for ($i = 0; $i < count ($data); i++){
         $images .= '<img src="/kittens/t/$i">');
    }

    $CatLife = 'Images of our kittens:<br>'.$images.'';
    echo $CatLife;

Try this, it stores each image tag into a string and echos it to the page.试试这个,它将每个图像标签存储到一个字符串中并将其回显到页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM