通过PHP回应一个动态的HTML图像路径

时间:2012-04-28 01:22:03

标签: php html

我试图在PHP中回显动态图像路径。我有这个代码可以工作

 <?php
 //this code works
 $image = '<img src="img/newlogo.jpg">';
 echo($image);
?>
//gives me an image

这段代码不是

 <?php
 //this code doesn't
 $lineofstring='newlogo.jpg';

 $image = '<img src="img/$lineofstring">';
 echo($image);
?>
$ lineofsting实际上是一个存储在mysql数据库中的图像路径,其中一行填充,例如:pictureabc.jpg,第二行是picturexyz.jpg等。

我试图将搜索到的图像路径名称传递到$ lineofstring,然后回显但没有图片出来。我哪里错了?

3 个答案:

答案 0 :(得分:4)

要在PHP中插入变量,您需要使用双引号",例如

$image = "<img src=\"img/$lineofstring\">";

在这种情况下,您需要转义内部"

您还可以使用.

连接字符串
$image = '<img src="img/' . $lineofstring . '">';

如果它更容易。

答案 1 :(得分:2)

您的$lineofstring变量位于使用单引号的字符串中。单引号告诉PHP按字面意思使用字符串,因此您的变量不会被识别为变量。将其更改为双引号或使用连接来实现目标。

$image = "<img src=\"img/$lineofstring\">";

或者:

$image = '"<img src="img'.$lineofstring.'">';

答案 2 :(得分:0)

$profilepicture="images/profiles/".$myid.".gif";
$noprofilepicture="images/profiles/no_avatar.gif";

echo "<IMG SRC='";
if (file_exists($profilepicture)) {
echo "".$profilepicture."";
} else {
echo "".$noprofilepicture."";
}
echo "'>";