img src 不适用于 php 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/693698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:32:11  来源:igfitidea点击:

img src won't work with php variables

phpvariablesimagesrc

提问by Kauthon

<a href="'.$productLink.'" alt="'.$productName.'">
<img src="'.$productImg1URL.'" alt="'.$productName.' '.$productType.' ">
</a>

Hello the img src is actually in a different directory /images

你好 img src 实际上在不同的目录 /images

I know this is probably super easy but Ive spent an hour on it and nothing. The page works but doesn't show the directory. Please help the rookie. I took out the < in front of the a href and img src couldn't make the page display

我知道这可能非常简单,但我花了一个小时,什么也没做。该页面有效但不显示目录。请帮助菜鸟。我把ahref前面的<去掉,img src无法让页面显示

回答by cletus

There are two ways of doing this:

有两种方法可以做到这一点:

Firstly, outside of a code block:

首先,在代码块之外:

<?php
// code here
?>
<a href="<?= $productLink ?>" alt="<?= $productName ?>">
<!-- or -->
<img src="<?echo $productImgURL; ?> alt="<?php echo $productName . ' ' . $productType ?>">
</a>

The first form is called the short open tagand has to be enabled in your php.ini which it almost always is.

第一种形式称为short open 标签,必须在您的 php.ini 中启用,它几乎总是如此。

Or if you're doing this inside a code block:

或者,如果您在代码块中执行此操作:

<?php
echo <<<END
<a href="$productLink" alt="$productName">
<img src="$productImgLURL" alt="$productName $productType">
</a>
END

The <<<ENDis a heredocand I usually prefer it to using a big string within double quotes, which requires escaping contained double quotes.

<<<END是一个heredoc,我通常更喜欢在双引号内使用大字符串,这需要转义包含的双引号。

回答by Alister Bulman

Job #1 when you have a problem with code that is generating HTML, is look at the output source and compare it with what you expect. I've had problems like this before and they usually vanished when I stopped thinking about the PHP code, and looked at the actual output.

当您在生成 HTML 的代码时遇到问题时,工作 #1 是查看输出源并将其与您期望的进行比较。我以前遇到过这样的问题,当我停止思考 PHP 代码并查看实际输出时,它们通常会消失。

What is the content of $productImg1URL - and if the images that it's referencing are in the URL starting /images/ - does that start $productImg1URL. If it's just the name of an image, but without the path - you have to put that into place.

$productImg1URL 的内容是什么 - 如果它引用的图像在以 /images/ 开头的 URL 中 - 是否以 $productImg1URL 开头。如果它只是图像的名称,但没有路径 - 您必须将其放置到位。