动态地在php中包含多个文件以用于图像描述

时间:2010-04-06 22:41:40

标签: php

致力于将图像描述实现到php运行库,似乎无法弄清楚如何为每个单独的图像调用每个文本文件。我需要在图像的代码中放置一个div,然后调用include。

   //total number of images
   $total = 77;

   //max number of thumbnails per page
   $max = 9;

   //what image do we want to start from?
   $startcount = $_GET["start"];

   //if there is not a defined starting image, we start with the first
   if(empty($startcount))
    {
   $startcount = 0; 
  }

   //start off the loop at 1
   $loop = 1;


   //start the loop
   while($loop <= $max)
    {

   //for the picture labels
   $num = $startcount + $loop;

   if($num > $total)
    {
     $num = $num - 1;
     break;
    }

   // Add class="last" to every third list item
   if(is_int($num / 3))
    {
     $last = ' class="last"';
    }
   else
    {
     $last = "";
    }

   //the code for the image
   echo '

        <li'.$last.'><a href="images/portfolio/pic-'.$num.'.jpg" rel="milkbox[gall1]"><img src="images/portfolio/thumbs/pic-'.$num.'-thumb.jpg" width="256" height="138" alt="Thumbnail of image '.$num.'" /></a><div>'.$num.'</div></li>';

我看到我可以使用'。$ num。'按编号调用文本文件。 (我有77个单独的文本文件,每个文本中都有一个短语)但是如何告诉它调用文件?

3 个答案:

答案 0 :(得分:1)

假设描述文件的名称类似于“description_ $ num.txt”,您只需使用readfile

  echo "<li${last}><a href='images/portfolio/pic-${num}.jpg' rel='milkbox[gall1]'>
          <img src='images/portfolio/thumbs/pic-${num}-thumb.jpg' width='256' 
               height='138' alt='Thumbnail of image ${num}'/>
        </a><div>";
  readfile("description_${num}.txt");
  echo '</div></li>';

请注意,您没有在PHP中“调用”文件,您可以include(将它们解释为脚本)或读取它们(将它们转储到输出中)。

答案 1 :(得分:0)

对于每个文件,您需要执行以下操作:

<?php 
$f=fopen($file,'r'); 
$data=''; 
while(!feof($f)) 
    $data.=fread($f,$size); 
fclose($f); 

// do whatever you want with the file content.

?>

答案 2 :(得分:0)

我使用了file_get_contents,并将输出拆分了一下,以便您可以更轻松地修改它:

<?php
$total = 77;
$max = 9;
$startcount = $_GET["start"];
$loop = 1;
if(empty($startcount)) $startcount = 0; 

while($loop <= $max)
{
    $num = $startcount + $loop;
    if($num > $total)
    {
        $num--;
        break;
    }
    $last = ($num % 3 == 0 ? ' class="last"' : '');

    $output = "<li $last>";
    $output .= "<a href=\"images/portfolio/pic-$num.jpg\" rel=\"milkbox[gall1]\">";
    $output .= "<img src=\"images/portfolio/thumbs/pic-$num-thumb.jpg\" width=\"256\" height=\"138\" alt=\"Thumbnail of image $num\">";
    $output .= "</a>";
    $output .= "<div>";
    $output .= file_get_contents("textfile-" . $num . ".txt"); // assuming this is where you want the phrase
    $output .= "</div>";
    $output .= "</li>";

    echo $output;
}

?>