2012-04-28 101 views
0

我想在PHP中回显动态图像路径。我有这样的代码,工程通过PHP回声一个动态的HTML图像路径

<?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等

我试图将搜索到的imagepath名称传递到$ lineofstring,然后echo'd,但没有图片出来。我哪里错了?

+0

使用双引号。 – bfavaretto 2012-04-28 01:23:45

回答

4

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

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

在这种情况下,您需要跳过内部"

您也可以连接字符串与.

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

如果它更容易。

+1

您可以在回显的HTML中使用单引号以避免需要转义。 – philwinkle 2012-04-28 02:33:46

+0

坦克你基督教 – 2012-04-28 02:40:20

2

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

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

或者:

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

谢谢约翰,这有帮助 – 2012-04-28 02:39:23

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 "'>";